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
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.
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.");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With