views:

271

answers:

2

I access a RESTFUL url and get back results. The results are in JSON. I turn the response into a string via:

- (void)connectionDidFinishLoading:(NSURLConnection   *)connection {
NSString *json = [[NSString alloc] initWithBytes:[self.receivedData mutableBytes] length:[self.receivedData length] encoding:NSUTF8StringEncoding];

The json variable has a value of 0x0. When I mouse over it, I see <Invalid CFStringRef>. How can I debug this to tell why it is invalid? I render the JSON given back through the browser in A JSON parser. That checks out fine.

Results are given back by entering an ID in the URL. Other IDs return results without issue. The result set is fairly large.

+1  A: 

Use NSLog to look at the bytes.

Alex Reynolds
And if the bytes represent data as a string, you can cut and paste them into 0xED to make viewing super easy: http://www.suavetech.com/0xed/0xed.html
nall
+2  A: 

First I would use initWithData:encoding: to setup the NSString. Small difference, but that method is there for a reason.

Then, I would do a hexdump of self.receivedData to see what is actually in there. If that data is not properly UTF8 encoded then the initWithData:encoding: will fail.

(Google for NSData hex dump to find other people's utility functions to do this)

I have found that sometimes web services are sloppy with their encoding. So I usually implement a fallback like this:

NSString* html = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
if (html == nil) {
    html = [[NSString alloc] initWithData: data encoding: NSISOLatin1StringEncoding];
    if (html == nil) {
        html = [[NSString alloc] initWithData: data encoding: NSMacOSRomanStringEncoding];
    }
}

It is kind of sad that this is required but many web services are not written or configured properly.

St3fan
Thanks. Your technique is definitely giving back some better info.
4thSpace