如何在断开Internet连接时处理NSJSONSerialization的崩溃

bc *_*c a 4 iphone json web-services ios nsjsonserialization

我在我的应用程序中实现了Web服务.我的方式很典型.

- (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"];
....
Run Code Online (Sandbox Code Playgroud)

控制台错误消息:

*由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:'data parameter is nil'

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

Hot*_*cks 11

该错误告诉您"responseData"为零.避免异常的方法是测试"responseData",如果它是nil则不调用JSONObjectWithData.相反,你会觉得你应该为这个错误条件做出反应.


Par*_*att 9

responseData在将其传递给JSONObjectWithData:options:error:方法之前,您不会检查您的是否为零.

可能你应该试试这个:

- (void)receiveLatest:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    if(responseData != nil)
    {
         NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:responseData
                      options:kNilOptions
                      error:&error];
         NSString *Draw_539 = [json objectForKey:@"Draw_539"];
    }
    else
    {
         //Handle error or alert user here
    }
    ....
}
Run Code Online (Sandbox Code Playgroud)

编辑1:为了更好的做法,你应该检查方法error之后检查这个对象JSONObjectWithData:options:error:,看看JSON数据是否成功转换为NSDictionary

- (void)receiveLatest:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    if(responseData != nil)
    {
         NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:responseData
                      options:kNilOptions
                      error:&error];
         if(!error)
         {
              NSString *Draw_539 = [json objectForKey:@"Draw_539"];
         }
         else
         {
              NSLog(@"Error: %@", [error localizedDescription]);
              //Do additional data manipulation or handling work here.
         } 
    }
    else
    {
         //Handle error or alert user here
    }
    ....
}
Run Code Online (Sandbox Code Playgroud)

希望这能解决您的问题.

如果您需要更多帮助,请告诉我.