简体   繁体   中英

How to prevent app crashing when uploading image when there is no internet connection

I have the objective C code:

NSString * url = [NSString stringWithFormat:@"http://tragicclothing.co.uk/Retort/imageupload.php"];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSMutableData *body = [[NSMutableData alloc]init];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: audio/basic\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:_imageDataToSend];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    //Send the Request
    NSData* returnData = [NSURLConnection sendSynchronousRequest: request
                                               returningResponse: nil error: nil];
    //serialize to JSON
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];

    //parsing JSON
    bool success = [result[@"success"] boolValue];
    if(success){ 
        NSLog(@"Success=%@",result[@"msg"]); 
    }else{ 
        NSLog(@"Fail=%@",result[@"msg"]);
    }

And it works fine when connected to the internet but when it is not I get the error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

if (!returnData){
    return; // or handle no connection error here
}else{
   NSDictionary *result = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];

    //parsing JSON
    bool success = [result[@"success"] boolValue];
   if(success){ 
        NSLog(@"Success=%@",result[@"msg"]); 
   }else{ 
       NSLog(@"Fail=%@",result[@"msg"]);
   }
}

You have to check for connectivity before performing network request.

Once you have downloaded and imported Reachbility.m and Reachbility.h files

create a helper function:

-(BOOL)IsConnected{
  Reachability *reachability = [Reachability reachabilityForInternetConnection];
  NetworkStatus networkStatus = [reachability currentReachabilityStatus];

  return !(networkStatus == NotReachable);    
}

Then use it

if([self IsConnected]){
 //connected!
 //upload your image
}
else{
  //not connected to internet!
}

Very important

If your project is not using arc

  • go to target >
  • Build Phase >
  • double click the Reachability file
  • add -fno-objc-arc

The app is crashing on this line

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];

because the value of returnData is nil. All you need to do is test if this object is nil before passing into NSJSONSerialization like so

NSData* returnData = [NSURLConnection sendSynchronousRequest: request
                                           returningResponse: nil error: nil];

if (returnData == nil)
{
    // Handle No Data returned from server
    // This can happen from no internet connection, from a server error or many other things
}
else 
{
    // Parse the Data
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];

    //parsing JSON
    bool success = [result[@"success"] boolValue];
    if(success){ 
        NSLog(@"Success=%@",result[@"msg"]); 
    }else{ 
        NSLog(@"Fail=%@",result[@"msg"]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM