IOS(object-c) 下载查看 PDF 其实仍是蛮容易操做的。在下载前,首先要把 IOS 能够保存文件的目录给过一遍:html
IOS 文件保存目录git
IOS 能够自定义写入的文件目录,是颇有限的,只能是这3个目录:github
1. NSDocumentDirectoryweb
下载文件到该目录,则该文档能够用 iTunes 直接查看。对于安全性不高,便于浏览的文件,pdf ,能够考虑下载到该目录。、缓存
2. NSLibraryDirectory安全
下载文件到该目录,则该文档不可用 iTunes 直接查看。只能在 APP 内部查看,对于文件有安全性方面的考虑,能够下载到该 目录。网络
3.NSCachesDirectoryapp
该目录存放的主要是缓存文件,如 图片的缓存数据等。不适合存放永久性的文件。网站
IOS 下载 pdf 文件url
在 IOS 开发过程当中一直使用的都是 AFNetworking( https://github.com/AFNetworking/AFNetworking) 负责的网络通讯,而且 这个开源的组件很稳定,也很易用,同时使用的人也是蛮多的,网上各类解决方案都很好找。此次下载也是用的 这个组件。
//设置下载文件保存的目录 NSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString* _filePath = [paths objectAtIndex:0]; //File Url NSString* fileUrl = @"http://.../...pdf"; //Encode Url 若是Url 中含有空格,必定要先 Encode fileUrl = [fileUrl stringByReplacingOccurrencesOfString:@" " withString:@"%20"]]; //建立 Request NSURLRequest* 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, long long totalBytesRead, long long totalBytesExpectedToRead) { //下载的进度,如 0.53,就是 53% float progress = (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]; }