一、從系統(tǒng)“文件”APP選擇文件上傳
#import "ViewController.h"
@interface ViewController () <UIDocumentPickerDelegate>
@property (nonatomic, strong) UIDocumentPickerViewController *documentPickerVC;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)tapSelectFileAction:(id)sender {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self presentViewController:self.documentPickerVC animated:YES completion:nil];
});
}
/**
初始化 UIDocumentPickerViewController
@param allowedUTIs 支持的文件類型數(shù)組
"public.content",
"public.text",
"public.source-code",
"public.image",
"public.audiovisual-content",
"com.adobe.pdf",
"com.apple.keynote.key",
"com.microsoft.word.doc",
"com.microsoft.excel.xls",
"com.microsoft.powerpoint.ppt"
@param mode 支持的共享模式
*/
- (UIDocumentPickerViewController *)documentPickerVC {
if (!_documentPickerVC) {
NSArray *types = @[@"public.content",@"public.text"];
self.documentPickerVC = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
// 設(shè)置代理
_documentPickerVC.delegate = self;
// 設(shè)置模態(tài)彈出方式
_documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
}
return _documentPickerVC;
}
#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 {
// 上傳
NSLog(@"fileName : %@", fileName);
// [self uploadingWithFileData:fileData fileName:fileName fileURL:newURL];
}
[self dismissViewControllerAnimated:YES completion:NULL];
}];
[urls.firstObject stopAccessingSecurityScopedResource];
} else {
// 授權(quán)失敗
}
}
@end
二恐似、從開(kāi)發(fā)APP中保存文件到系統(tǒng)“文件”APP
#pragma mark - 下載文件
/// http://jadinec-test.oss-accelerate.aliyuncs.com/excelFile/a5f23e130d5e4dd7adda942c45207927.pdf
- (void)downLoadWithFilePath:(NSString *)filePath {
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version >= 11) {
} else {
[MBProgressHUD showError:@"下載文件要求手機(jī)系統(tǒng)版本在11.0以上"];
return;
}
/**
/// 保存網(wǎng)絡(luò)文件到沙盒一
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:filePath]];
NSData *fileData = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSString *temp = NSTemporaryDirectory();
NSFileManager *fm = [NSFileManager defaultManager];
NSString *fullPath = [self getNativeFilePath:[filePath componentsSeparatedByString:@"/"].lastObject];
BOOL downResult = [fm createFileAtPath:fullPath contents:fileData attributes:nil];
*/
/// 保存網(wǎng)絡(luò)文件到沙盒二
NSData *fileData = [NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]];
NSString *fullPath = [self getNativeFilePath:[filePath componentsSeparatedByString:@"/"].lastObject];
BOOL downResult = [fileData writeToFile:fullPath atomically:YES];
if (downResult) {
UIDocumentPickerViewController *documentPickerVC = [[UIDocumentPickerViewController alloc] initWithURL:[NSURL fileURLWithPath:fullPath] inMode:UIDocumentPickerModeExportToService];
// 設(shè)置代理
documentPickerVC.delegate = self;
// 設(shè)置模態(tài)彈出方式
documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
[self.navigationController presentViewController:documentPickerVC animated:YES completion:nil];
}
}
// 獲得文件沙盒地址
- (NSString *)getNativeFilePath:(NSString *)fileName {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *munu = [NSString stringWithFormat:@"%@/%@",@"downLoad",fileName];
NSString *filePath = [path stringByAppendingPathComponent:munu];
// 判斷是否存在,不存在則創(chuàng)建
NSFileManager *fileManager = [NSFileManager defaultManager];
// fileExistsAtPath 判斷一個(gè)文件或目錄是否有效,isDirectory判斷是否一個(gè)目錄
BOOL isDir = NO;
NSMutableArray *theArr = [[filePath componentsSeparatedByString:@"/"] mutableCopy];
[theArr removeLastObject];
NSString *thePath = [theArr componentsJoinedByString:@"/"];
BOOL existed = [fileManager fileExistsAtPath:thePath isDirectory:&isDir];
if ( !(isDir == YES && existed == YES) ) { // 如果文件夾不存在
[fileManager createDirectoryAtPath:thePath withIntermediateDirectories:YES attributes:nil error:nil];
}
return filePath;
}
#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 {
// 上傳
NSLog(@"fileName : %@", fileName);
}
}];
[urls.firstObject stopAccessingSecurityScopedResource];
} else {
// 授權(quán)失敗
}
}