开发者

Strange error with initWithContentsOfURL

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

The following code works fine:

NSError *error = nil;

NSString *xmlString = [[NSString alloc] initWithContent开发者_高级运维sOfURL: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


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.


Try this: 1) Create NSData using dataWithContentsOfURL 2)No create xmlString only when NSData created above is not null, i.e passes check if(data)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜