2015-07-20 23 views
2

我正在使用NSURLSessionNSURLSessionTask下載應用程序中的文件。如果文件存在於服務器上,那麼它工作正常。如果文件不可用,那麼它將數據寫入文件並且不要下載它。 例如::如果文件不可用的寫入iOS ::如果無法使用NSURLSession下載文件,則錯誤爲零

訪問該文件中被拒絕

,並沒有任何錯誤完成任務。在這種情況下,錯誤爲零。

但我想顯示警告框給用戶說文件不可用。

下面是代碼...

task1 = [session dataTaskWithURL:[NSURL URLWithString:[S3_SERVER_URL stringByAppendingString:propFile]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
      propfilePath = [[Util getInAppTempPath] stringByAppendingString:propFile]; 
      NSLog(@"DestPath : %@", propfilePath); 
      [receivedData appendData:data]; 
      NSLog(@"Succeeded! Received %lu bytes of data",(unsigned long)[data length]); 
      //[UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
      [data writeToFile:propfilePath atomically:YES]; 

      //NSLog(@"iOSDBVersion: %@", [plistDictionary objectForKey:@"iOSDBVersion"]); 
      //NSLog(@"ttodDBVersion: %@", [plistDictionary objectForKey:@"ttodDBVersion"]); 
      if(error == nil){ 
       [Util getDataFromPlistFile]; 
       [Util isAppRunBefore]; 
       [self downloadDatabase]; 

      } else { 
       [self alertNoPlist]; 
      } 

     }]; 
     [task1 resume]; 

它從未進入else塊。

我累了把這個放在try catch block那麼也沒有運氣。

如何處理iOS中的這些錯誤?

+0

您是否嘗試過在該完成塊中設置斷點來查看設置的內容?我懷疑你說「它永遠不會進入其他區塊」,因爲你沒有看到警報;但我不認爲這是足夠好的證據(即ale​​rtview可能不會顯示爲線程不是主線程)。 – trojanfoe

+0

是的,我在開始時保持斷點...它給出的錯誤是零,響應一些十六進制值,數據爲250字節... – Anjali

+0

檢查響應的狀態代碼。 –

回答

4

我假設服務器正在返回一個響應代碼,如401(未授權),以及諸如「訪問被拒絕」之類的主體。這在NSURLSession意義上不是錯誤。這是完全合法的迴應,因此您不會期望error中的任何內容。

取而代之,您需要檢查響應的值statusCode值。這應該在200-299之間取得成功。正如我所說,你可能會得到401.

請注意,你通過了NSURLResponse。您可能需要將其轉換爲NSHTTPURLResponse以訪問其statusCode

+0

感謝羅布......它的工作... – Anjali

0

您正在使用dataTaskWithURL:下載圖像。對於下載任務,您應該使用downloadTaskWithURL:

[[session downloadTaskWithURL:[NSURL URLWithString:[S3_SERVER_URL stringByAppendingString:propFile]] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) 
{ 
    if (error) 
    { 
     // Show error 
    } 
    else 
    { 
     [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:propfilePath] error:nil]; 
    } 
}] resume]; 

欲瞭解更多詳情,請參閱:

  1. NSURLSessionDownloadTask
  2. NSURLSessionDataTask
1

使用下面的代碼來獲取的HttpResponse狀態代碼。

NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; 
      NSLog(@"response status code: %ld", (long)[httpResponse statusCode]);