, .
PHAsset
PHAsset+Picking.h
#import <Photos/Photos.h>
@interface PHAsset (Picking)
+ (PHAsset *)retrievePHAssetWithLocalIdentifier:(NSString *)identifier;
+ (void)saveVideoFromCameraToPhotoAlbumWithInfo:(NSDictionary *)info
completion:(void(^)(PHAsset * _Nullable asset))completion;
@end
PHAsset+Picking.m
@implementation PHAsset (Picking)
+ (PHAsset *)retrievePHAssetWithLocalIdentifier:(NSString *)identifier {
PHAsset *asset = nil;
if (identifier) {
PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[identifier] options:nil];
asset = result.firstObject;
}
return asset;
}
+ (void)saveVideoFromCameraToPhotoAlbumWithInfo:(NSDictionary *)info
completion:(void(^)(PHAsset * _Nullable asset))completion
{
NSURL *url = info[UIImagePickerControllerMediaURL];
__block PHAssetChangeRequest *changeRequest = nil;
__block PHObjectPlaceholder *assetPlaceholder = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
changeRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:url];
assetPlaceholder = changeRequest.placeholderForCreatedAsset;
} completionHandler:^(BOOL success, NSError *error) {
if (success) {
PHAsset *asset = [PHAsset retrievePHAssetWithLocalIdentifier:assetPlaceholder.localIdentifier];
completion(asset);
} else {
completion(nil);
}
}];
}
@end
saveVideoFromCameraToPhotoAlbumWithInfo
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
Weakify(self);
void (^processAsset)(PHAsset *, NSDictionary *) = ^void(PHAsset *asset, NSDictionary *mediaInfo) {
[PHImageManager.defaultManager requestAVAssetForVideo:asset
options:nil
resultHandler:^(AVAsset *asset,
AVAudioMix *audioMix,
NSDictionary *assetInfo)
{
Strongify(self);
if ([asset respondsToSelector:@selector(URL)]) {
NSURL *videoURL = [asset performSelector:@selector(URL)];
} else {
}
}];
};
if (UIImagePickerControllerSourceTypeCamera == picker.sourceType) {
[PHAsset saveVideoFromCameraToPhotoAlbumWithInfo:info completion:^(PHAsset *asset) {
processAsset(asset, info);
}];
} else {
processAsset(info[UIImagePickerControllerPHAsset], info);
}
} else {
}
}