前言:
最近做了一個(gè)項(xiàng)目吧寺,需要實(shí)現(xiàn)能夠選取圖片或者word、pdf散劫、txt等文檔類型的文件并進(jìn)行上傳稚机,并且能夠?qū)崿F(xiàn)文件的下載和預(yù)覽功能,以前沒(méi)有做過(guò)相關(guān)的功能获搏,所以在網(wǎng)上查找相關(guān)資料之后赖条,終于實(shí)現(xiàn)了,現(xiàn)分享下瀏覽和預(yù)覽文件的實(shí)現(xiàn)過(guò)程:
一、文件瀏覽
實(shí)現(xiàn)文件瀏覽有以下兩個(gè)類:
1纬乍、UIDocumentBrowserViewController
這個(gè)是用于瀏覽本地和云中存儲(chǔ)的文件并對(duì)其執(zhí)行操作碱茁,由于是iOS11之后新出的并沒(méi)有使用到它,這里就不講述這個(gè)是如何實(shí)現(xiàn)的仿贬。
2纽竣、UIDocumentPickerViewController
我所使用的就是這個(gè)類,打破應(yīng)用沙盒的限制茧泪,提供對(duì)應(yīng)用沙盒外的文件或目標(biāo)的訪問(wèn)蜓氨。具體代碼如下:
創(chuàng)建:
//懶加載
- (UIDocumentPickerViewController *)documentPickerVC {
if (!_documentPickerVC) {
/**
初始化
@param allowedUTIs 支持的文件類型數(shù)組
@param mode 支持的共享模式
*/
self.documentPickerVC = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:self.documentTypes inMode:UIDocumentPickerModeOpen];
//設(shè)置代理
_documentPickerVC.delegate = self;
//設(shè)置模態(tài)彈出方式
_documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
}
return _documentPickerVC;
}
實(shí)現(xiàn)代理方法:
#pragma mark - UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
//獲取授權(quán)
BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
if (fileUrlAuthozied) {
//通過(guò)文件協(xié)調(diào)工具來(lái)得到新的文件地址,以此得到文件保護(hù)功能
NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
NSError *error;
[fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
//讀取文件
NSString *fileName = [newURL lastPathComponent];
NSError *error = nil;
NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
if (error) {
//讀取出錯(cuò)
} else {
//上傳
[self uploadingWithFileData:fileData fileName:fileName fileURL:newURL];
}
[self dismissViewControllerAnimated:YES completion:NULL];
}];
[urls.firstObject stopAccessingSecurityScopedResource];
} else {
//授權(quán)失敗
}
}
在代理方法里可以選取得到文件队伟,再進(jìn)行上傳或者其他操作穴吹。
文件瀏覽實(shí)現(xiàn)效果圖:(由于是模擬器截圖,所以沒(méi)有任何文件嗜侮,見(jiàn)諒8哿睢)
PS:
至于圖片選取和瀏覽,大家都比較熟悉棘钞,這里就不再?gòu)U話了。
二干毅、文件預(yù)覽
文件預(yù)覽我使用的是UIDocumentInteractionController宜猜,這個(gè)類可以預(yù)覽,打開(kāi)或打印其文件格式無(wú)法直接由您的應(yīng)用程序處理的文件硝逢。實(shí)現(xiàn)代碼如下:
創(chuàng)建對(duì)象:
//懶加載
- (UIDocumentInteractionController *)documentInteractionC {
if (!_documentInteractionC) {
//初始化
self.documentInteractionC = [[UIDocumentInteractionController alloc] init];
//設(shè)置代理
_documentInteractionC.delegate = self;
}
return _documentInteractionC;
}
實(shí)現(xiàn)代理方法:
#pragma mark - UIDocumentInteractionControllerDelegate
//返回一個(gè)視圖控制器姨拥,代表在此視圖控制器彈出
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
return self;
}
//返回一個(gè)視圖,將此視圖作為父視圖
- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller {
return self.view;
}
//返回一個(gè)CGRect渠鸽,做為預(yù)覽文件窗口的坐標(biāo)和大小
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller {
return self.view.frame;
}
得到文件的URL叫乌,指定URL并打開(kāi)預(yù)覽窗口:
NSURL *URL = self.fileURLArray[indexPath.row];
if ([URL isFileURL]) {
if ([[[NSFileManager alloc] init] fileExistsAtPath:URL.path]) {
//指定預(yù)覽文件的URL
self.documentInteractionC.URL = URL;
//彈出預(yù)覽文件窗口
[self.documentInteractionC presentPreviewAnimated:YES];
} else {
[SVProgressHUD showErrorWithStatus:@"該文件不存在!"];
}
} else {
if ([URL.scheme containsString:@"http"]) {
UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"不存在本地文件,需要下載徽缚,是否下載憨奸?" preferredStyle:UIAlertControllerStyleAlert];
[alertC addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//文件存儲(chǔ)路徑
NSString *filePathString = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:URL.absoluteString.lastPathComponent];
NSURLSessionDownloadTask *downloadTask = [self.manager downloadTaskWithRequest:[NSURLRequest requestWithURL:URL] progress:^(NSProgress * _Nonnull downloadProgress) {
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//返回文件存儲(chǔ)路徑
return [NSURL fileURLWithPath:filePathString];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//下載完成后,替換原來(lái)的URL凿试,下次不用再下載排宰,直接打開(kāi)
[self.fileURLArray replaceObjectAtIndex:indexPath.row withObject:filePath];
//指定預(yù)覽文件的URL
self.documentInteractionC.URL = filePath;
//彈出預(yù)覽文件窗口
[self.documentInteractionC presentPreviewAnimated:YES];
}];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
MBProgressHUD *hud = [MBProgressHUD HUDForView:self.view];
hud.label.text = @"正在下載文件";
//啟動(dòng)下載文件任務(wù)
[downloadTask resume];
}]];
[alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:alertC animated:YES completion:^{
}];
} else {
[SVProgressHUD showErrorWithStatus:@"該文件鏈接不存在!"];
}
}
文件預(yù)覽實(shí)現(xiàn)效果圖:
到這里就簡(jiǎn)單的實(shí)現(xiàn)文件的選取、瀏覽和預(yù)覽了那婉,如果寫(xiě)得有什么錯(cuò)誤的地方板甘,歡迎大家批評(píng)指正!