1

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

我有一些奇怪的东西,我无法弄清楚。当我检查服务器是否没有响应(离线)而不是通过取回 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(错误)条件并不能防止崩溃......

任何人都可以帮助我吗?

谢谢!

4

1 回答 1

5

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

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

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

于 2016-03-13T11:35:31.827 回答