gpt4 book ai didi

ios - 如何在Objective-C中捕获JSON错误?

转载 作者:行者123 更新时间:2023-12-01 17:57:34 25 4
gpt4 key购买 nike

遵循本教程: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'而终止应用程序,原因:'数据参数为nil'”

如何捕获此错误?我只想显示一个警报消息,而不是中断。

解析JSON数据时会发生几种错误?

最佳答案

您应该检查NSData* data是否为nil?如果为零,则不应运行代码行

NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data 
options:kNilOptions
error:&error];

当您尝试将 nil数据转换为 Dictionary时。

您还可以通过在代码中实现可达性类来检查网络可用性。一个示例应用程序演示了如何使用SystemConfiguration框架来监视iPhone或iPod touch的网络状态。

http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html

关于ios - 如何在Objective-C中捕获JSON错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14575350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com