一. 相冊內(nèi)數(shù)據(jù)轉(zhuǎn)沙盒應用場景
- 使用ReplayKit時,需要將保存到相冊的視頻上傳至服務器,這時需要把相冊的數(shù)據(jù)轉(zhuǎn)換到沙盒中.
二. Photos庫--從相冊取最近一次的圖片/視頻復制一份到沙盒
- 注意: ALAssetLibrary在ios8已經(jīng)過期,操作相冊蘋果推薦用更新的Photos類庫,此處使用Photos類庫講解,ALAssetLibrary不再闡述.
- 訪問相冊需要提前獲取相冊權(quán)限,修改權(quán)限會重啟應用
基本思路
- PHAsset 對象能獲取圖片相關的信息,非圖片本身.
- 相冊和沙盒都在一個文件系統(tǒng)中,所以不需要把相冊圖片/視頻全部加載到內(nèi)存中(會導致內(nèi)存暴增)再存儲
- 使用PHAssetResource和PHAssetResourceManager就可以直接復制圖片/視頻到沙盒中,不會導致內(nèi)存暴增.
- 使用assetResourcesForAsset:方法可以把PHAsset轉(zhuǎn)化為PHAssetResource
1.判斷相冊權(quán)限
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];
//創(chuàng)建保存到沙盒的路徑
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(@"保存沙盒失敗,重新嘗試");
}
}];
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者