How to get the URL of an image just added in PHPhotoLibrary

后端 未结 6 928
臣服心动
臣服心动 2020-12-30 03:11

I am using the UIImagePickerController in two cases

  • to select an existing image in the Photo Library
  • to take a new picture

In the first

6条回答
  •  时光取名叫无心
    2020-12-30 03:48

    I didn't find the way to get URL, but maybe localIdentifier can help you do the same work.

    use

    NSString* localId = [[assetChangeRequest placeholderForCreatedAsset] localIdentifier];
    

    to get the local ID and get the image later.

    __block NSString* localId;
    // Add it to the photo library
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
    
        if (self.assetCollection) {
            PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:self.assetCollection];
            [assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];
        }
        localId = [[assetChangeRequest placeholderForCreatedAsset] localIdentifier];
    } completionHandler:^(BOOL success, NSError *error) {
        PHFetchResult* assetResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[localId] options:nil];
        if (!success) {
            NSLog(@"Error creating asset: %@", error);
        } else {
            PHFetchResult* assetResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[localId] options:nil];
            PHAsset *asset = [assetResult firstObject];
            [[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
                UIImage* newImage = [UIImage imageWithData:imageData];
                self.imageView.image = newImage;
            }];
        }
    }];
    

提交回复
热议问题