App的沙盒文件共享到系统的“文件”App(Files)

167 阅读1分钟

权限设置:

Info.plist 中添加两个键值对,

第一个是 UIFileSharingEnabled,这个可以使 iTunes 分享你文件夹内的内容;

第二个是 LSSupportsOpeningDocumentsInPlace ,它保证了你文件夹内本地文件的获取权限;

将这两个键值对的值设置为 YES.

完整沙盒目录:

IMG_0191.PNG

系统的文件App展示结果:

截屏2025-04-07 16.09.27.png

示例文件类型:(文档、音频、视频等)

.json .pdf .docx .MOV .mp3 .png .html .rtf 

示例代码:


- (void)button1Clicked:(UIButton *)sender {
    NSLog(@"按钮1被点击");
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
                                                         NSDocumentDirectory,
                                                         NSUserDomainMask,
                                                         YES
                                                         );
    NSString *docPath = [paths firstObject];  //
    
    UIImage *image = [UIImage imageNamed:@"test.png"];
    NSData *data = UIImagePNGRepresentation(image);
    NSString *imagePath = [docPath stringByAppendingPathComponent:@"imagetest.png"];
    [data writeToFile:imagePath atomically:YES];  //
}


- (void)button2Clicked:(UIButton *)sender {
    NSLog(@"按钮2被点击");
    // 获取Bundle内MP3路径
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"okkk" ofType:@"mp3"];
    if (!bundlePath) {
        NSLog(@"错误:项目未找到okkk.mp3文件");
        return;
    }
    // 获取Document目录路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPath = [paths firstObject];  //示例:/var/mobile/Containers/Data/Application/.../Documents

    // 目标路径
    NSString *destPath = [docPath stringByAppendingPathComponent:@"audio.mp3"];

    // 文件复制
    NSFileManager *manager = [NSFileManager defaultManager];
    NSError *error = nil;
    if ([manager fileExistsAtPath:destPath]) {
        [manager removeItemAtPath:destPath error:&error];  // 删除已存在
    }
    BOOL success = [manager copyItemAtPath:bundlePath toPath:destPath error:&error];

    if (success) {
        NSLog(@"文件已写入:%@", destPath);
        // 验证文件是否存在
        if ([manager fileExistsAtPath:destPath]) {
            NSLog(@"写入验证成功");
        }
    } else {
        NSLog(@"复制失败:%@", error.localizedDescription);
    }
    
}