This problem has already been mentioned elsewhere but the solution was dealing with error. And here I think I manage my error correctly (but it sound like I am mistaken...).
I've got something strange I cannot figure out. My app crashes when I check if a server is not responding (offline) and not by getting back a JSON object. In my memories this was working before I dealt with iOS 9.2.
Using exception breakpoint, I can see it has to do with a data parameter which is "nil" when creating a dictionary (which is normal I guess since the server is offline and not returning anything) but the crash should be avoided by managing the error... which does not seem to be the case in my code.
A few lines:
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];
}
It sounds like the if (error) condition does not prevent from crashing...
Anyone could help me?
Thanks!
You should just add a if block after before initizaling your JSON. Such as:
if(rawData != nil) {
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:dataRaw
options:kNilOptions error:&error];
}
After that you can handle your error if it is not nil.