項(xiàng)目需要用戶可以上傳自己的一些ppt,doc,pdf文檔等。利用UIDocumentPickerViewController就可以幫助我們?cè)L問(wèn)本地的文件達(dá)到上傳的目的凌蔬。
需要讓iOS程序支持iTunes文件交換需要在程序的Info.plist里增加一個(gè)鍵:UIFileSharingEnabled(Application supports iTunes file sharing)炫掐,賦值YES潭苞。
然后就是代碼操作了庶诡。
首先初始化UIDocumentPickerViewController
// 項(xiàng)目支持可以選擇的文件類型
NSArray*types = @[
@"com.microsoft.powerpoint.ppt",
@"com.microsoft.word.doc",
@"org.openxmlformats.wordprocessingml.document",
@"org.openxmlformats.presentationml.presentation",
@"public.mpeg-4",
@"com.adobe.pdf",
@"public.mp3"
? ? ? ? ];
//初始化
self.documentPicker = [[UIDocumentPickerViewControlleralloc]? initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
self.documentPicker.delegate =self;
//全屏彈出
self.documentPicker.modalPresentationStyle =UIModalPresentationFullScreen;
//設(shè)置模態(tài)彈出方式
//self.documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[[UIApplicationsharedApplication].keyWindow.rootViewController presentViewController:self.documentPicker animated:YEScompletion:nil];
然后直接實(shí)現(xiàn)UIDocumentPickerDelegate的方法就可以獲取到本地文件的數(shù)據(jù)了
#pragmamark - UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController*)controller didPickDocumentsAtURLs:(NSArray *)urls {
//獲取授權(quán)
BOOLfileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
if(fileUrlAuthozied) {
NSFileCoordinator*fileCoordinator = [[NSFileCoordinatoralloc] init];
NSError*error;
[fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0error:&error byAccessor:^(NSURL*newURL) {
//讀取文件
NSString*fileName = [newURL lastPathComponent];
NSError*error =nil;
NSData*fileData = [NSDatadataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafeerror:&error];
// 上傳規(guī)則
/*
? ? ? ? ? ? ? ? 走項(xiàng)目數(shù)據(jù)上傳接口就可以了
? ? ? ? ? ? */
[[UIApplicationsharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:YEScompletion:NULL];
? ? ? ? }];
? ? ? ? [urls.firstObject stopAccessingSecurityScopedResource];
}else{
//授權(quán)失敗
[LCSCustomToast showWithMessage:@"授權(quán)失敗唬血,請(qǐng)您去設(shè)置頁(yè)面打開(kāi)授權(quán)"image:@"login_fail_image"];
return;
? ? }
}