前提:UIDocumentPicker,AFNetWorking
1、注册
2、代理回调
在UIDocumentPickerDelegate的- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls API_AVAILABLE(ios(11.0))方法里面处理回调事件
#pragma mark - UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
//获取授权
WeakSelf
BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
if(fileUrlAuthozied) {
NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
__block NSError*error;
[fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
// 读取文件
NSString*fileName = [newURLlastPathComponent];
NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
NSString *newNameStr = [fileName stringByRemovingPercentEncoding];
NSArray *fileArray = [newNameStr componentsSeparatedByString:@"."];
if(error) {
// 出错
}else{
// 上传
NSString *mimeType = [NSString stringWithFormat:@"file/%@",fileArray.lastObject];
// 调用AFN,上传文件到自己的服务器
[ASLNetToolEngine uploadFileWithFileData:fileData fileName:fileName mimeType:mimeType completionHandle:^(ResponseModel*response) {
if(response.code==0) {
// 上传成功
}else{
// 上传失败
}
} errorHandle:^(NSError*error) {
}];
}
[weakSelf dismissViewControllerAnimated:YES completion:NULL];
}];
[urls.firstObject stopAccessingSecurityScopedResource];
} else {
//授权失败
}
}