iOS   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 使用AFNetworking 2.0下载PDF大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在做一个简单的请求,以下载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:使用下载文件的完整路径创建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];

大佬总结

以上是大佬教程为你收集整理的ios – 使用AFNetworking 2.0下载PDF全部内容,希望文章能够帮你解决ios – 使用AFNetworking 2.0下载PDF所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: