按照本教程:http ://www.raywenderlich.com/5492/working-with-json-in-ios-5 ,我制作了这样的简单应用程序:
#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
当网络不正常或 JSON 链接错误时,我得到相同的中断:“ *由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:'数据参数为零”
如何捕捉这个错误?我只想显示一条警报消息,而不是中断。
解析 JSON 数据时有多少种错误?