7

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

Community
  • 1
  • 1
swdev
  • 4,997
  • 8
  • 64
  • 106
  • 1
    The downside of that one-liner is that it blocks your UI, possibly for a long time. The loop is even worse: if the server is not responding to connections, then it would block the UI effectively forever (until SpringBoard gets fed up and kills your process). – Peter Hosey Oct 31 '11 at 19:27

3 Answers3

20

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.

Brigham
  • 14,395
  • 3
  • 38
  • 48
  • thanks @Brigham for that info. But, the problem is, it sometimes null, sometimes not. So, I just force it to try it until it's not null. If using dataWithContentsOfURL:options:error, how do you handle such? – swdev Oct 31 '11 at 06:21
  • 1
    @swdev: You look at the error to find out what went wrong, and react appropriately to what went wrong. Usually this will be presenting the error to the user. – Peter Hosey Oct 31 '11 at 19:25
3

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.");
}
ylgwhyh
  • 1,588
  • 18
  • 21
0

check your network connection. If it is connected then the problem will solve.

Ram Madhavan
  • 2,362
  • 1
  • 17
  • 20