管理错误时 NSURLSession 崩溃,JSON 数据参数为零

NSURLSession crash with JSON data parameter is nil while error is managed

这个问题已经在其他地方提到过,但解决方案是处理错误。在这里,我认为我正确地管理了我的错误(但听起来我错了......)。

我有一些奇怪的事情我想不通。当我检查服务器是否没有响应(离线)而不是通过取回 JSON 对象时,我的应用程序崩溃了。在我的记忆中,这在我处理 iOS 9.2.

之前是有效的

使用异常断点,我可以看到它与创建字典时 "nil" 的数据参数有关(我猜这是正常的,因为服务器离线并且没有返回任何东西)但是崩溃应该通过管理错误来避免......这在我的代码中似乎不是这种情况。

几行:

NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; // url with php script have been set before...

[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[noteDataString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *dataRaw, NSURLResponse *response, NSError *error) {
    NSDictionary *json = [NSJSONSerialization
                          JSONObjectWithData:dataRaw
                          options:kNilOptions error:&error];

    // I thought this condition below should manage the error when the json dictionary cannot be set because of the nil "dataRay" paramater but my app crashes.
    if (error) {
        UIAlertView * av = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Checking permission:\nGot error %@.\n", error] message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [av show];
        // (I know UIAlertView is deprecated in iOS 9.0 :-)...)
    }

    NSString *status = json[@"status"];

    if([status isEqual:@"1"]){
        //Success in php script

        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"It works" message:nil delegate:self cancelButtonTitle:@"Cool" otherButtonTitles:nil, nil];
        [av show];

    }

听起来 if(错误)条件并不能防止崩溃...

有人能帮帮我吗?

谢谢!

您应该在初始化 JSON 之前添加一个 if 块。如:

if(rawData != nil) {
    NSDictionary *json = [NSJSONSerialization
                          JSONObjectWithData:dataRaw
                          options:kNilOptions error:&error];
}

之后你可以处理你的错误,如果它不是零。