网上很多PHAsset转UIImage的代码,没有UIImage转PHAsset的,今天有个同学刚好问,我正好研究一下,直接上代码吧:
UIImage*image = [UIImageimageNamed:@"image"];
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
PHAssetChangeRequest *request = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
NSString *localIndentifier = request.placeholderForCreatedAsset.localIdentifier;
PHFetchResult*assetResult = [PHAssetfetchAssetsWithLocalIdentifiers:@[localIndentifier]options:nil];
PHAsset*asset = assetResult.firstObject;
}error:nil];
另外需要注意,转换代码一定要写在PHPhotoLibrary的
- (void)performChanges:(dispatch_block_t)changeBlock completionHandler:(nullable void(^)(BOOL success, NSError *__nullable error))completionHandler;
或者
- (BOOL)performChangesAndWait:(dispatch_block_t)changeBlock error:(NSError *__autoreleasing *)error;
中,不然会报异常:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This method can only be called from inside of -[PHPhotoLibrary performChanges:completionHandler:] or -[PHPhotoLibrary performChangesAndWait:error:]'
网友评论