PDF与AFNetworking 2.0下载

问题描述:

我正在做一个简单的请求,以下载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://*.com/questions/1759956/curl-error-18-transfer-closed-with-outstanding-read-data-remaining – Mateusz 2015-02-25 12:14:49

请试试这个例子。希望这个帮助!

//第一步:创建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];