Why does NSData dataWithContentsOfURL sometimes return NULL?

I thank with gratitude for the article Convert NSData bytes to NSString? , especially for @ christo16. I was previously dependent on ASIHttpRequest to get the value from a PHP server. Now, using only this line of code:

NSString *pageContents = [NSData dataWithContentsOfURL: [NSURL URLWithString:@"http://www.apple.com"]] 

I can get the functionality that I wanted.

But why sometimes this line calls pageContents as NULL. I am already changing this line in this:

 NSString *fullUrl = [NSString stringWithFormat:@"http://www.apple.com"]; NSURL *url = [[NSURL alloc] initWithString:fullUrl]; NSData *pageContents; NSString *response = NULL; while(response==NULL) { pageContents = [NSData dataWithContentsOfURL: [NSURL URLWithString:fullUrl]]; response = [NSString stringWithUTF8String:[pageContents bytes]]; NSLog(@"content = %@", response); } 

Is there a better way to do this? I still have no problems. I just wonder if there is a more elegant way to achieve the same result.

thanks

+7
source share
3 answers

It will return nil if a data retrieval error occurs.

You can use the message dataWithContentsOfURL:options:error: to find out why it returns zero. The error will be returned by the NSError* pointer that you pass.

+18
source

The image may be too large or the URL is incorrect.

 NSError* error = nil; NSData* data = [NSData dataWithContentsOfURL:yourURL options:NSDataReadingUncached error:&error]; if (error) { NSLog(@"%@", [error localizedDescription]); } else { NSLog(@"Data has loaded successfully."); } 
+1
source

check network connection. If it is connected, the problem will be solved.

0
source

All Articles