【问题标题】:How to prevent app crashing when uploading image when there is no internet connection如何防止在没有互联网连接时上传图像时应用程序崩溃
【发布时间】:2014-04-25 06:32:39
【问题描述】:

我有目标 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”而终止应用程序,原因:“数据参数为零”

【问题讨论】:

  • 一般情况下,您应该检查返回值和错误代码。您还应检查响应中的 HTTP 状态代码以及 MIME 类型。你没有,因此你不知道出了什么问题;)
  • 不要使用同步请求,除非整个代码在单独的线程中运行。使用异步而不是阻止用户界面。

标签: ios objective-c


【解决方案1】:
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"]);
   }
}

【讨论】:

    【解决方案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

    【讨论】:

    • 最好只尝试网络请求,只有IFF无法建立连接,测试可达性。
    • 那是另一种方式,我也看到有人ping google。
    • 如何导入 .h 和 .m 两个文件?我已经完成了:#import "Reachability.h" #import "Reachability.m"
    • 我收到一个错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
    • 是的,下载文件,将它们添加到您的项目中,然后只导入.h file #import Reachability.h
    【解决方案3】:

    应用程序在这条线上崩溃

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

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      相关资源
      最近更新 更多