ios – 使用AFNetworking 2.0下载PDF

ios – 使用AFNetworking 2.0下载PDF,第1张

概述我正在做一个简单的请求,以下载PDF文件,然后将其写入文件路径. 一些PDF被定向到失败块. 我得到的错误代码是200,错误描述是“传输关闭,剩余2231939字节读取”. 以下是代码段. NSURLRequest *request = [NSURLRequest requestWithURL:url cac 我正在做一个简单的请求,以下载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所遇到的程序开发问题。

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1044826.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存