簡體   English   中英

在沒有互聯網連接的情況下如何防止應用程序在上傳圖像時崩潰

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

我有目標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”

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

您必須在執行網絡請求之前檢查連接性。

下載並導入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

該應用程序在此行崩潰

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM