網(wǎng)上很多PHAsset轉(zhuǎn)UIImage的代碼,沒有UIImage轉(zhuǎn)PHAsset的,今天有個同學(xué)剛好問,我正好研究一下,直接上代碼吧:
? ? 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];
另外需要注意,轉(zhuǎn)換代碼一定要寫在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:]'