views:

584

answers:

1

I'm currently working on reading some XML from an external API.

The following code works fine:

NSError *error = nil;

NSString *xmlString = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

However, I wanted to add some error handling ("The server cannot be reached", "No Internet connection" etc). So, I put this block in place with a little help from the Reachability sample code:

if ([error code] == kCFURLErrorNotConnectedToInternet) {
        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedString(@"No Internet connection",@"Error message displayed when not connected to the Internet.") forKey:NSLocalizedDescriptionKey];
        NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:userInfo];
        [self handleError:noConnectionError];
    } else {
        // otherwise handle the error generically
        [self handleError:error];
    }

The handleError method simply displays a UIAlertView with the error's details. When I ran the app with no connection, I expected to see my error message. However, all I ever get is "Operation could not be completed (Cocoa error 256)" which from what I can gather is a generic read error.

At first I thought it might just be TouchXML's method, but as you can see I changed this to NSString's initWithCOntentsOfURL.

Can anyone shed any light on this issue?

Thanks,

Rich

A: 

You seeing some other error than kCFURLErrorNotConnectedToInternet. The error message is not coming from your custom error but is generated by some object under the hood. You need to dump the userInfo dict of the error you actually get to see the details. I would log it instead of using an alert to make sure you get all of it.

If the userInfo dict is actually empty, I would start by testing the url to see if it actually returns anything. Try initializing a data object and see what you get. That will narrow it down between a problem with the URL and a problem with converting the data into a string.

TechZen
When connected to the Internet, the XML is downloaded and put into a string or touchxml object just fine. It's when not connected I need the error - it's just that this error seems like the wrong one! Rich
Rich