一. 相册内数据转沙盒应用场景
- 使用ReplayKit时,需要将保存到相册的视频上传至服务器,这时需要把相册的数据转换到沙盒中.
二. Photos库--从相册取最近一次的图片/视频复制一份到沙盒
- 注意: ALAssetLibrary在ios8已经过期,操作相册苹果推荐用更新的Photos类库,此处使用Photos类库讲解,ALAssetLibrary不再阐述.
- 访问相册需要提前获取相册权限,修改权限会重启应用
基本思路
- PHAsset 对象能获取图片相关的信息,非图片本身.
- 相册和沙盒都在一个文件系统中,所以不需要把相册图片/视频全部加载到内存中(会导致内存暴增)再存储
- 使用PHAssetResource和PHAssetResourceManager就可以直接复制图片/视频到沙盒中,不会导致内存暴增.
- 使用assetResourcesForAsset:方法可以把PHAsset转化为PHAssetResource
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(@"保存沙盒失败,重新尝试");
}
}];
}