iOS读取相册信息保存到本地(最简)

注:上边文正提到过在苹果6上取相册视频地址,取不到的情况,针对上篇文章在iOS12之后的缺陷,做出了如下的调整


代码截图.jpg

详细代码

 //获取最近一次的相册图片/视频的信息PHAsset
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    // 进行排序
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
    // 将最新写入相册的获取出来,我这里最新写入的是视频,需要获取额的也是视频
     PHAsset *phasset = [assetsFetchResults lastObject];
    if (phasset) {
        if (phasset.mediaType == PHAssetMediaTypeVideo) {
            PHImageManager *manager = [PHImageManager defaultManager];
            [manager requestAVAssetForVideo:phasset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
                AVURLAsset *urlAsset = (AVURLAsset *)asset; // 注:这里需要注意,假如我们没有进行排序,那么在苹果6上,我们这里获取到的是 nil
                NSLog(@"%@",urlAsset.URL);
                // 文件保存路径
                NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
                NSString *path = [documentsDirectory stringByAppendingPathComponent:@"record.mp4"];
                NSData *data = [NSData dataWithContentsOfURL:urlAsset.URL];
                NSFileManager *mag =[NSFileManager defaultManager];
                // 判断文件是不是存在
                if (![mag fileExistsAtPath:path]) {
                    [data writeToFile:path atomically:YES];
                }else{
                    [mag removeItemAtPath:path error:nil];
                    [data writeToFile:path atomically:YES];
                }
            }];
        }
    }

重点:在 iOS12之后,必须加上排序的代码,不然在苹果6上取不到视频的地址。验证在别的机型上暂时没有问题,针对苹果6。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。