2015-02-23 70 views
4

我正在做一個簡單的請求,以下載PDF文件,然後將其寫入文件路徑。 一些PDF正被引導到失敗塊。 我收到的錯誤代碼是200,錯誤描述是「傳輸關閉,剩餘2231939字節要讀取」。 以下是代碼片段。PDF與AFNetworking 2.0下載

NSURLRequest *request = [NSURLRequest requestWithURL:url 
              cachePolicy:nil 
             timeoutInterval:120]; 

    AFHTTPRequestOperation *downloadRequest = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 

    [downloadRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
     if (operation.response.statusCode != 200) { 
      NSLog(@"Error code(S): %d",[operation.response statusCode]); 
     }else{ 
      NSData *data = [[NSData alloc] initWithData:responseObject]; 

      [data writeToFile:filePath atomically:YES]; 
      NSLog(@"successful download to %@", filePath); 

      [data release]; 
     }    
     [self fetchComplete:operation type:type]; 

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"error code: %d",[operation.response statusCode]); 
     NSLog(@"error discreption: %@",[error localizedDescription]); 
     [self fetchFailed:operation]; 
    }]; 
+0

如果只有部分文件使這個問題,可能您的服務器可以重置連接?有沒有關於錯誤描述的其他信息? – kocakmstf 2015-02-25 11:33:02

+0

檢查此問題http://stackoverflow.com/questions/1759956/curl-error-18-transfer-closed-with-outstanding-read-data-remaining – Mateusz 2015-02-25 12:14:49

回答

3

請試試這個例子。希望這個幫助!

//第一步:創建NSURL,下載文件的完整路徑 //例如試試這個:NSString * fileUrl = @「https://pbs.twimg.com/profile_images/2331579964/jrqzn4q29vwy4mors75s_400x400.png」; //並與我們的URL創建的NSURLRequest對象

NSURL *URL = [NSURL URLWithString:fileUrl]; 
NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

//第2步:保存下載文件的文件名 //例如我們的文件名字符串等於 'jrqzn4q29vwy4mors75s_400x400.png'

NSString *fileName = [URL lastPathComponent]; 

//步驟3:用我們的請求創建AFHTTPRequestOperation對象

AFHTTPRequestOperation *downloadRequest = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 

//第4步:設置服務器應答與請求d錯誤

[downloadRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
      // here we must create NSData object with received data... 
      NSData *data = [[NSData alloc] initWithData:responseObject]; 
      // ... and save this object as file 
      // Here 'pathToFile' must be path to directory 'Documents' on your device + filename, of course 
      [data writeToFile:pathToFile atomically:YES]; 
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
      NSLog(@"file downloading error : %@", [error localizedDescription]); 
     }]; 

//第5步:開始異步下載

[downloadRequest start];