<UIDocumentPickerDelegate> @property (nonatomic, strong) UIDocumentPickerViewController *documentPickerVC; /** 初始化 UIDocumentPickerViewController 選文件啊 @param allowedUTIs 支持的文件類型數組 "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",@"public.image",@"com.adobe.pdf",@"com.microsoft.word.doc",@"com.microsoft.excel.xls",@"com.microsoft.powerpoint.ppt"]; self.documentPickerVC = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen]; // 設置代理 _documentPickerVC.delegate = self; // 設置模態彈出方式 _documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet; } return _documentPickerVC; } #pragma mark - UIDocumentPickerDelegate - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls { // 獲取授權 BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource]; if (fileUrlAuthozied) { // 通過文件協調工具來得到新的文件地址,以此得到文件保護功能 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]; NSLog(@"fileData.bytes : %dKB \n bytes : %ldKB",1024*1024*10,fileData.length); if (error) { // 讀取出錯 } else { if (fileData.length<1024*1024*10) { //小於10MB // 上傳 }else{ NSLog(@"文件大小不能超過10MB"); } NSLog(@"fileName : %@", fileName); } }]; [urls.firstObject stopAccessingSecurityScopedResource]; } else { // 授權失敗 } }