I am trying to get the source of a url, so that I can parse through the HTML code to get information. I have the following code:
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSError *err = nil;
NSString *urlContents = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&err];
if(err){
NSLog(@"err %@",err);
}
NSLog(@"urlContents %@", urlContents);
This code works perfectly on the simulator, but on a device I get the following error:
err Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x167150 {NSURL=http://www.google.com}
That usually means the internet is down on your device. Or perhaps the encoding you're trying to force the web page to be loaded as is not the one that matches NSUTF8String encoding.
Trying changing your code to this:
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSError *err = nil;
NSStringEncoding encoding;
NSString *urlContents = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&err];
if(urlContents)
{
NSLog(@"urlContents %@", urlContents);
} else {
// only check or print out err if urlContents is nil
NSLog(@"err %@",err);
}
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