美文网首页来不及读的文字
IOS下载查看PDF文件(有下载进度)

IOS下载查看PDF文件(有下载进度)

作者: 6bbe3ffd9b9b | 来源:发表于2017-06-12 18:11 被阅读196次

    IOS(object-c) 下载查看 PDF 其实还是蛮容易操作的。在下载前,首先要把 IOS 可以保存文件的目录给过一遍:

    IOS 文件保存目录

    IOS 可以自定义写入的文件目录,是很有限的,只能是这3个目录:

    1. NSDocumentDirectory

    下载文件到该目录,则该文档可以用 iTunes 直接查看。对于安全性不高,便于浏览的文件,pdf ,可以考虑下载到该目录。、

    2. NSLibraryDirectory

    下载文件到该目录,则该文档不可用 iTunes 直接查看。只能在 APP 内部查看,对于文件有安全性方面的考虑,可以下载到该 目录。

    3.NSCachesDirectory

    该目录存放的主要是缓存文件,如 图片的缓存数据等。不适合存放永久性的文件。

    IOS 下载 pdf 文件

    在 IOS 开发过程中一直使用的都是 AFNetworking(

    https://github.com/AFNetworking/AFNetworking) 负责的网络通信,并且

    这个开源的组件很稳定,也很易用,同时使用的人也是蛮多的,网上各种解决方案都很好找。这次下载也是用的 这个组件。

    //设置下载文件保存的目录NSArray* paths =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

    NSString* _filePath = [paths objectAtIndex:0];//File UrlNSString* fileUrl =@"http://.../...pdf";//Encode Url 如果Url 中含有空格,一定要先 EncodefileUrl = [fileUrl stringByReplacingOccurrencesOfString:@""withString:@"%20"]];//创建 RequestNSURLRequest* request =[NSURLRequest requestWithURL:[NSURL URLWithString:fileUrl]];

    NSString* fileName =@"down_form.pdf";

    NSString* filePath =[_filePath stringByAppendingPathComponent:fileName];//下载进行中的事件AFURLConnectionOperation *operation =[[AFHTTPRequestOperation alloc] initWithRequest:request];

    operation.outputStream=[NSOutputStream outputStreamToFileAtPath:filePath append:NO];

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead,longlongtotalBytesRead,longlongtotalBytesExpectedToRead) {//下载的进度,如 0.53,就是 53%floatprogress =  (float)totalBytesRead /totalBytesExpectedToRead;//下载完成//该方法会在下载完成后立即执行if(progress ==1.0) {

    [downloadsTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]  withRowAnimation:UITableViewRowAnimationAutomatic];

    }

    }];//下载完成的事件//该方法会在下载完成后 延迟 2秒左右执行//根据完成后需要处理的及时性不高,可以采用该方法[operation setCompletionBlock:^{

    }];

    [operation start];

    查看 PDF 文件

    IOS 下查看 PDF 文件的方法是蛮多的,但是 WebView 最简单便捷,虽然不是最强大的。

    NSArray* paths =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

    NSString* filePath = [paths objectAtIndex:0];

    NSString* fileName =@"down_form.pdf";

    NSString*path =[filePath stringByAppendingPathComponent:fileName];

    BOOL fileExists=[[NSFileManager defaultManager] fileExistsAtPath:path];if(fileExists) {

    path=[Util urlEncodeString:path];

    NSURL* url =[[NSURL alloc]initWithString:path];

    NSURLRequest*request =[NSURLRequest requestWithURL:url];

    [webView loadRequest:request];

    }

    相关文章

      网友评论

        本文标题:IOS下载查看PDF文件(有下载进度)

        本文链接:https://www.haomeiwen.com/subject/kktrqxtx.html