Here is my question. How do I display an error if my app is unable to load my remote JSON file? I turned my wifi off on my computer and ran the app in the Simulator. It NSLogs the message that should be displayed if there is connection. How can I fix this? Thanks.
Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *jsonStr = @"http://xxx.com/server.php?json=1";
NSURL *jsonURL = [NSURL URLWithString:jsonStr];
// NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
// NSError *jsonError = nil;
NSURLRequest *jsonLoaded = [NSURLRequest requestWithURL:jsonURL];
if(!jsonLoaded) {
UIAlertView *alertView = [[UIAlertView alloc] init];
alertView.title = @"Error!";
alertView.message = @"A server with the specified hostname could not be found.\n\nPlease check your internet connection.";
[alertView addButtonWithTitle:@"Ok"];
[alertView show];
[alertView release];
NSLog(@"No connection, JSON not loaded...");
}
else {
NSLog(@"JSON loaded and ready to process...");
}
}
Your code just creates the request. It doesn’t actually fetch the data. You need to use
NSURLConnectionto fetch the data.There are multiple ways to fetch the data. This example is for iOS 5.0 or higher: