Follow this tutorial: http://www.raywenderlich.com/5492/working-with-json-in-ios-5 , I make simple App like that:
#define kLatestKivaLoansURL [NSURL URLWithString: @"http://api.kivaws.org/v1/loans/search.json?status=fundraising"]
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL];
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:@"loans"];
NSLog(@"Error: %@",error);
NSLog(@"loans: %@",latestLoans);
dispatch_async(dispatch_get_main_queue(), ^(){
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
});
});
return YES;
}
@end
When Network not OK or JSON link Error, I get same break: “* Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘data parameter is nil”
How to catch this Error? I just want to display an Alert message, not break.
How many kind of Errors when parse JSON data?
You should implement a check on
NSData* datawhether it is nil or not? If its nil then you should not run the code lineas you are trying to convert
nildata intoDictionary.You can also check network availability by implementing Reachability classes in you code. A sample application demonstrates how to use the SystemConfiguration framework to monitor the network state of an iPhone or iPod touch
http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html