欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS13上传相册视频Code=1 "Operation not permitted"

程序员文章站 2024-03-19 08:07:58
...

iOS13上传相册视频Code=1 “Operation not permitted”

在做文件上传时候,发现iOS13上,选择相册的视频上传,会报无权限访问文件的错误,iOS13以下的系统不会出这个问题,可能部分机型上会有吧,但是我没发现。

报错信息:
Error Domain=NSCocoaErrorDomain Code=257 "The file "trim.166DC0B6-0C86-4EC3-BCBD-F29684A5566C/tmp/1C91514D-C987-4C1C-BEBF-6A7F071F1435.MOV" couldn't be opened because you don't has permission to view it."

iOS13上传相册视频Code=1 "Operation not permitted"

看了下iOS12和iOS13上获取到的文件路径:

iOS12
file:///private/var/mobile/Containers/Data/Application/166DC0B6-0C86-4EC3-BCBD-F29684A5566C/tmp/1C91514D-C987-4C1C-BEBF-6A7F071F1435.MOV";

iOS13
file:///private/var/mobile/Containers/Data/Application/PluginKitPgin/166DC0B6-0C86-4EC3-BCBD-F29684A5566C/tmp/1C91514D-C987-4C1C-BEBF-6A7F071F1435.MOV";

发现iOS12的路径多了一个PluginKitPgin文件夹,这导致文件访问受限。

但是有意思的是通过iOS13的这个路径可以拿到问价你的二进制数据

+ (NSData *)fileData:(NSString *)filePath {
    NSFileHandle *fileHande = [NSFileHandle fileHandleForReadingAtPath:filePath];
    return [fileHande readDataToEndOfFile];
}

这样的话先拿到文件,然后写入沙盒,然后通过沙盒路径去上传就ok了,大致代码是这样的:

//视频文件
if ([mediaType isEqualToString:@"public.movie"])
{
    NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL];
    NSString *videoPath = url.path;

    // <13.0可以直接上传
    if ([[UIDevice currentDevice].systemVersion floatValue] < 13.0)
    {
        //上传
        [self addUploadFileWithPath:videoPath];
    }
    //13.0 先将文件存在在沙盒,然后上传
    else
    {
        NSString *datapath = [self writeFileToDocPaths:videoPath];
        [self addUploadFileWithPath:datapath];
    }
}

将数据写入沙盒中

-(NSString *)writeFileToDocPaths:(NSString *)filePath {
    //读取相册中的文件
    NSData *data = [VHUploaderModel fileData:filePath];
    //将文件写入沙盒
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *dataPath = [self getFilePath:[NSString stringWithFormat:@"%@",[filePath lastPathComponent]]];
    if (![fileManager fileExistsAtPath:dataPath]) {//文件是否存在
        [fileManager createFileAtPath:dataPath contents:nil attributes:nil];
    }
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:dataPath];
    [fileHandle seekToEndOfFile];
    [fileHandle writeData:data];
    [fileHandle closeFile];
    return dataPath;
}
- (NSString *)getFilePath:(NSString *)fileName {
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES).firstObject;
    return [docPath stringByAppendingPathComponent:fileName];
}