+[NSURL URLWithString:] returning nil

北城余情 提交于 2019-12-06 09:46:55

for some weird reason I have to use :
[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

when I create the URL and this solved the issue.

Krumelur

NSData initWithContentsOfURL: returns nil if the data cannot be loaded (i.e. if you get a HTTP error code).

Chances are the URL you point to has some referrer blocker or cookie requirement that prevents its use from within your app (just one suggestion of the problem).

I recommend you look at using the following variant instead:

- (id)initWithContentsOfURL:(NSURL *)aURL options:(NSDataReadingOptions)mask error:(NSError **)errorPtr

And pay attention to the value of errorPtr in case the return value is nil.

For example:

NSError *error;
NSData* imageData = [[NSData alloc] initWithContentsOfURL:
    [NSURL URLWithString:@"http://example.com/notfound"]
    options:0 error:&error];
if(imageData == nil) {
    NSLog(@"Error: %@", error);
} else {
    NSLog(@"Got %u bytes", imageData.length);
}

You can see the following error:

Error: Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0xa881c20 {NSURL=http://example.com/notfound}

If you load the image like that it's blocking the main thread and leaving your application unresponsive and I'm not sure if the initWithContentsOfURL: method is handling redirects at all if that is the issue... You can create another class (ImageFetcher for example) that uses NSURLConnection and implements the NSURLConnectionDataDelegate. Using the connection:willSendRequest:redirectResponse: method from the NSURLConnectionDataDelegate you can handle redirects and in the connection:didReceiveData: method you can append the received data to a NSMutableData (it's not guaranteed that you receive all the data in one go). Furthermore you don't have to wait for the connection to finish or download any data if you implement the connection:didReceiveResponse: method and check if the response is indicating an error and in the connectionDidFinishLoading: method you can call another method to update your image view (or call the delegate of the ImageFetcher class with the appropriate data to update the image view).

NSURL URLWithString:@"" will return nil if the URL does not conform to RFC 2396 and they must be escaped

If you read through rfc2396 in the link you will get loads of details

A great site I found for checking where the offending character is, choose the path option for URL

http://www.websitedev.de/temp/rfc2396-check.html.gz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!