4

我在我的应用程序中实现了 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"];
....

控制台错误信息:

*由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“数据参数为零”

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

4

2 回答 2

12

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

于 2013-08-06T12:04:23.403 回答
9

responseData在将它传递给JSONObjectWithData:options:error:方法之前,您没有检查您是否为 nil。

也许你应该试试这个:

- (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
    }
    ....
}

EDIT-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
    }
    ....
}
于 2013-08-06T05:48:00.933 回答