音视频相关音视频及流媒体

iOS 自动上传相册中视频/图片--相册视频/图片转沙盒

2017-07-11  本文已影响268人  Jesscia_Liu

一. 相册内数据转沙盒应用场景

二. Photos库--从相册取最近一次的图片/视频复制一份到沙盒

基本思路

1.判断相册权限

AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        MLNewCustomDialog *ncd=[[MLNewCustomDialog alloc] initWithTitle:@"温馨提示" andMoreText:@"请您设置允许本应用访问您的相机\n设置>隐私>相机" andButton1:@"好的" andButton2:nil andBackViewForBlurImage:self.view];
        ncd.delegate=self;
        [self.view addSubview:ncd];
        [ncd show];
        return ;
    }

2.拷贝相册中最近一次的图片/视频到沙盒中,方便上传到服务器.

#import <Photos/Photos.h>

- (void)saveVideoSuccess:(void(^)())success{
    //获取最近一次的相册图片/视频的信息PHAsset
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
    options.includeAssetSourceTypes = PHAssetSourceTypeNone;//默认相册
    PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
    PHAsset *asset = [assetsFetchResults firstObject];
    PHAssetResource *assetRescource = [[PHAssetResource assetResourcesForAsset:asset] firstObject];
    
    //创建保存到沙盒的路径
    NSString *uuidString = [[NSUUID UUID] UUIDString];
    NSString *fileName = uuidString;
    NSString *documentPath = [NSString stringWithFormat:@"%@/photosFile", [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir= NO;
    BOOL existed = [fileManager fileExistsAtPath:documentPath isDirectory:&isDir];
    if (!(existed&&isDir)){
        [fileManager createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *filePath=[documentPath stringByAppendingPathComponent:fileName];
    
    //保存到沙盒
     __weak typeof(self) weakSelf = self;
    PHAssetResourceManager *manager = [PHAssetResourceManager defaultManager];
    [manager writeDataForAssetResource:assetRescource toFile:[NSURL fileURLWithPath:filePath] options:nil completionHandler:^(NSError * _Nullable error) {
        if (error==nil) {
            if(success)success();
            NSLog(@"保存沙盒成功");
            [self showStudentAndTeacherView];
        }else{
            [weakSelf saveVideoSuccess:success];
            NSLog(@"保存沙盒失败,重新尝试");
        }
    }];
}
上一篇 下一篇

猜你喜欢

热点阅读