目錄:
一志衍、 WKWebView
加載本地或者網(wǎng)絡pdf文檔
二慧起、 利用QLPreviewController
加載pdf文檔 (系統(tǒng)框架<QuickLook/QuickLook.h>
)
三译暂、 利用PDFView
(系統(tǒng)框架<PDFKit/PDFKit.h>
)打開
特別說明??:加載網(wǎng)絡pdf文檔最好下載到本地然后加載永淌,不然可能會卡頓濒生,有時還有莫名的加載失敗甚至閃退...
第一種:WKWebView
加載本地或者網(wǎng)絡pdf文檔
- 按照這種方式和普通的加載html沒有任何區(qū)別健爬,這里小編就不做多余的贅述控乾;
- 存在的問題??:加載pdf后,再push到另外一個頁面娜遵,返回到
WKWebView
頁面蜕衡,原先的內(nèi)容不見了,會變成空白一片;
第二種:利用QLPreviewController
加載pdf文檔 ,首先判斷是否加載到本地设拟,如果有直接加載本地的慨仿,如果沒有就進行文件下載久脯,然后加載文件:
- (void)viewDidLoad {
[super viewDidLoad];
self.previewController = [[QLPreviewController alloc] init];
self.previewController.dataSource = self;
}
// 預覽網(wǎng)絡文件
- (void)previewInternet {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSString *urlStr = self.url;
NSString *fileName = [urlStr lastPathComponent]; //獲取文件名稱
NSURL *URL = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
//判斷是否存在
if([self isFileExist:fileName]) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
self.fileURL = url;
[self presentViewController:self.previewController animated:YES completion:nil];
//刷新界面,如果不刷新的話,不重新走一遍代理方法镰吆,返回的url還是上一次的url
[self.previewController refreshCurrentPreviewItem];
}else {
[SVProgressHUD showWithStatus:@"下載中"];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){
} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
return url;
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
[SVProgressHUD dismiss];
self.fileURL = filePath;
[self presentViewController:self.previewController animated:YES completion:nil];
//刷新界面,如果不刷新的話帘撰,不重新走一遍代理方法,返回的url還是上一次的url
[self.previewController refreshCurrentPreviewItem];
}];
[downloadTask resume];
}
}
//判斷文件是否已經(jīng)在沙盒中存在
-(BOOL) isFileExist:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *filePath = [path stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL result = [fileManager fileExistsAtPath:filePath];
return result;
}
#pragma mark - QLPreviewControllerDataSource
-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
return self.fileURL;
}
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)previewController{
return 1;
}
第三種:利用PDFView
(系統(tǒng)框架<PDFKit/PDFKit.h>
)打開
首先判斷是否加載到本地万皿,如果有直接加載本地的摧找,如果沒有就進行文件下載,然后加載文件:
注意??:本框架在
iOS11.0+
后可用
-(void)setupPDF{
self.pdfView = [[PDFView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight + 44, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight - 44)];
self.pdfView.autoScales = YES;
self.pdfView.userInteractionEnabled = YES;
[self.view addSubview:self.pdfView];
if ([self.urlString isNoEmpty]) {
self.sourceURL = [NSURL URLWithString:self.urlString];
}else{
return;
}
//路徑作為緩存key
_cacheFileKey = self.sourceURL.absoluteString;
__weak __typeof(self) wself = self;
_queryCacheOperation = [[WebCacheHelpler sharedWebCache] queryDataFromMemory:_cacheFileKey cacheQueryCompletedBlock:^(id data, BOOL hasCache) {
dispatch_async(dispatch_get_main_queue(), ^{
if(hasCache) {
wself.pdfDocument = [[PDFDocument alloc] initWithData:data];
wself.pdfDocument.delegate = self;
wself.pdfView.document = self.pdfDocument;
}else{
[wself startDownloadTask:_sourceURL isBackground:YES];
}
});
}];
}
//開始資源下載任務
- (void)startDownloadTask:(NSURL *)URL isBackground:(BOOL)isBackground {
__weak __typeof(self) wself = self;
_queryCacheOperation = [[WebCacheHelpler sharedWebCache] queryDataFromMemory:_cacheFileKey cacheQueryCompletedBlock:^(id data, BOOL hasCache) {
dispatch_async(dispatch_get_main_queue(), ^{
if(hasCache) {
wself.pdfDocument = [[PDFDocument alloc] initWithData:data];
wself.pdfDocument.delegate = self;
wself.pdfView.document = self.pdfDocument;
return;
}
if(wself.combineOperation != nil) {
[wself.combineOperation cancel];
}
[WEHUD showWaitHUD];
wself.combineOperation = [[WebDownloader sharedDownloader] downloadWithURL:URL responseBlock:^(NSHTTPURLResponse *response) {
} progressBlock:^(NSInteger receivedSize, NSInteger expectedSize, NSData *data) {
} completedBlock:^(NSData *data, NSError *error, BOOL finished) {
if(!error && finished) {
//下載完畢牢硅,將緩存數(shù)據(jù)保存到本地
[[WebCacheHelpler sharedWebCache] storeDataToDiskCache:data key:wself.cacheFileKey];
}
[WEHUD hideHUD];
wself.pdfDocument = [[PDFDocument alloc] initWithData:data];
wself.pdfDocument.delegate = self;
wself.pdfView.document = self.pdfDocument;
} cancelBlock:^{
[WEHUD hideHUD];
[WEHUD showWarningHUD:@"文件下載失敗"];
} isBackground:isBackground];
});
}];
}