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