Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why NSData dataWithContentsOfURL sometimes return NULL value?

I am gratefully thanks for the article Convert NSData bytes to NSString?, especially for @christo16. I was previously dependent on ASIHttpRequest just to get value from PHP server. Now using by just this line of code :

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

I can get the functionality that I wanted.

But why is sometimes that line cause pageContents to be NULL. I already change that line into 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 any better way of doing this? Up until now, I have no problem. I just wonder whether there is a more elegant way of achieving the same result

Thanks

like image 358
swdev Avatar asked Oct 31 '11 05:10

swdev


2 Answers

It will return nil if there is an error retrieving the data.

You can use the dataWithContentsOfURL:options:error: message to find out why it's returning nil. The error will be returned in the NSError* pointer that you pass.

like image 113
Brigham Avatar answered Nov 09 '22 08:11

Brigham


Probably the picture is too big or 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.");
}
like image 45
ylgwhyh Avatar answered Nov 09 '22 08:11

ylgwhyh