Search code examples
iphoneobjective-cnsmutableurlrequestnsmutabledata

How to find why NSMutableData is invalid


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.


Solution

  • 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.