iphone - 断开互联网连接时如何处理 NSJSONSerialization 的崩溃

标签 iphone ios json web-services nsjsonserialization

我在我的应用程序中实现网络服务。我的方式很典型。

- (BOOL)application:(UIApplication *)application     didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Web Service  xxx,yyy are not true data
    NSString *urlString =   @"http://xxx.byethost17.com/yyy";
    NSURL *url = [NSURL URLWithString:urlString];
    dispatch_async(kBackGroudQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: url];
        [self performSelectorOnMainThread:@selector(receiveLatest:)     withObject:data waitUntilDone:YES];
    });   
    return YES;
}

- (void)receiveLatest:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:responseData
                      options:kNilOptions
                      error:&error];
    NSString *Draw_539 = [json objectForKey:@"Draw_539"];
....

控制台错误信息:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

当我的 iPhone 连接到互联网时,该应用程序成功运行。但如果它断开与互联网的连接,应用程序将在 NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; 上崩溃 你能告诉我如何处理这个错误吗? NSError 有帮助吗?

最佳答案

错误告诉您“responseData”为零。避免异常的方法是测试“responseData”,如果它为 nil,则不调用 JSONObjectWithData。相反,您应该针对这种错误情况使用react。

关于iphone - 断开互联网连接时如何处理 NSJSONSerialization 的崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18069884/

相关文章:

json - 'dict' 对象在 Django Serializer 上没有属性 '_meta'

iphone - iOS:如何在输入文本字段后发送键盘

ios - 使用适用于 iOS 的 AddThis SDK,需要更改默认 Twitter 文本的 "via @AddThis"

ios - 如何在 Digits iOS SDK View 上应用自定义语言

c - 如何在 sqlite3 中将 json 数组索引设置为绑定(bind)参数?

java - 如何在没有 get/set 方法的情况下获取对象 JSON

ios - Xcode 自动布局设置

iphone - 如何根据文本调整iphone中自定义按钮的大小

iphone - 在 Xcode 中创建 Objective-C++ 静态库

objective-c - 为 hello world 启动什么样的项目重要吗?