iOS技术交流收藏iOS

访问沙盒外文档UIDocumentPickerViewContr

2018-06-05  本文已影响0人  莫云溪

官方文档解析

官方文档:https://developer.apple.com/documentation/uikit/uidocumentpickerviewcontroller?language=objc

UIDocumentPickerViewController有四种模式:

操作外部文件注意事项

调用Demo

展示文件选择

- (void)presentDocumentPicker {
    NSArray *types = @[]; // 可以选择的文件类型
    UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
    documentPicker.delegate = self;
    documentPicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:documentPicker animated:YES completion:nil];
}

用户选择文件回调

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
    BOOL canAccessingResource = [url startAccessingSecurityScopedResource];
    if(canAccessingResource) {
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
            NSData *fileData = [NSData dataWithContentsOfURL:newURL];
            NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentPath = [arr lastObject];
            NSString *desFileName = [documentPath stringByAppendingPathComponent:@"myFile"];
            [fileData writeToFile:desFileName atomically:YES];
            [self dismissViewControllerAnimated:YES completion:NULL];
        }];
        if (error) {
            // error handing
        }
    } else {
        // startAccessingSecurityScopedResource fail
    }
    [url stopAccessingSecurityScopedResource];
}

文件类型定义

initWithDocumentTypes:inMode:中,types需要传入一个uniform type identifiers (UTIs)数组。关于UTIs的官方文档,常见列表


欢迎关注我的博客

上一篇下一篇

猜你喜欢

热点阅读