UIDocumentPickerViewController获取本地文件

项目需要用户可以上传自己的一些ppt,doc,pdf文档等。利用UIDocumentPickerViewController就可以帮助我们访问本地的文件达到上传的目的。

需要让iOS程序支持iTunes文件交换需要在程序的Info.plist里增加一个键:UIFileSharingEnabled(Application supports iTunes file sharing),赋值YES。

然后就是代码操作了。

首先初始化UIDocumentPickerViewController

// 项目支持可以选择的文件类型

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;

//设置模态弹出方式

//self.documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;

[[UIApplicationsharedApplication].keyWindow.rootViewController presentViewController:self.documentPicker animated:YEScompletion:nil];

然后直接实现UIDocumentPickerDelegate的方法就可以获取到本地文件的数据了

#pragmamark - UIDocumentPickerDelegate

- (void)documentPicker:(UIDocumentPickerViewController*)controller didPickDocumentsAtURLs:(NSArray *)urls {

//获取授权

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];

// 上传规则

/*

                走项目数据上传接口就可以了

            */

[[UIApplicationsharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:YEScompletion:NULL];

        }];

        [urls.firstObject stopAccessingSecurityScopedResource];

}else{

//授权失败

[LCSCustomToast showWithMessage:@"授权失败,请您去设置页面打开授权"image:@"login_fail_image"];

return;

    }

}

你可能感兴趣的:(UIDocumentPickerViewController获取本地文件)