如何在没有互联网连接时上传图像时防止应用崩溃

时间:2014-04-24 22:08:25

标签: ios objective-c

我有目标C代码:

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"]);
    }

当连接到互联网时它工作正常,但是当它不是我得到错误时:

由于未捕获的异常终止应用' NSInvalidArgumentException',原因:'数据参数为nil'

3 个答案:

答案 0 :(得分:3)

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"]);
   }
}

答案 1 :(得分:2)

在执行网络请求之前,您必须检查连接性。

获得downloaded并导入Reachbility.mReachbility.h个文件

创建辅助函数:

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

  return !(networkStatus == NotReachable);    
}

然后使用它

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

非常重要

如果您的项目未使用arc

  • 转到目标>
  • 构建阶段>
  • 双击“可达性文件”
  • 添加-fno-objc-arc

答案 2 :(得分:1)

应用程序正在崩溃

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

因为returnData的值为nil。您需要做的就是在传递到NSJSONSerialization之前测试此对象是否为nil

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"]);
    }
}