使用AFNetworking 2.0下载PDF

时间:2015-02-23 12:32:47

标签: ios afnetworking afnetworking-2

我正在做一个简单的请求,以便下载PDF文件,然后将其写入文件路径。 一些PDF被定向到失败块。 我得到的错误代码是200,错误描述是"传输关闭,剩余2231939个字节用于读取"。 以下是代码段。

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

1 个答案:

答案 0 :(得分:3)

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

//步骤1:使用下载文件的完整路径创建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步:保存下载文件的名称 //例如我们的fileName字符串等于'jrqzn4q29vwy4mors75s_400x400.png'

NSString *fileName = [URL lastPathComponent];

//步骤3:使用我们的请求创建AFHTTPRequestOperation对象

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

//步骤4:设置服务器应答处理和请求错误

[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];