如何获取刚刚在PHPhotoLibrary中添加的图像的URL

Pat*_*ckV 16 url ios8 phphotolibrary

我在两种情况下使用UIImagePickerController

  • 选择照片库中的现有图像
  • 拍摄新照片

在第一种情况下,当我从库中选择一个图像时,我可以轻松地在委托方法中获取URL:

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // Get the URL
    NSURL *url = [info valueForKey:UIImagePickerControllerReferenceURL];
    ...
}
Run Code Online (Sandbox Code Playgroud)

但是,当我拍摄新照片时,图片尚未出现在照片库中,并且还没有网址.所以,我首先需要在库中添加图像.但是,如何获取新资产的URL?

这是我在照片库中添加图像的代码

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // Get the image
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

    // Add the image in the library
    [[PHPhotoLibrary sharedPhotoLibrary]

        performChanges:^
        {
            // Request creating an asset from the image.
            PHAssetChangeRequest *createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];

            // Get the URL of the new asset here ?
            ...
        }

        completionHandler:^(BOOL success, NSError *error)
        {
            if (!success) { ...; return; }

            // Get the URL of the new asset here ?
            ...
        }
    ];
}
Run Code Online (Sandbox Code Playgroud)

Rig*_*hen 10

我没有找到获取URL的方法,但也许localIdentifier可以帮助您完成相同的工作.

使用

NSString* localId = [[assetChangeRequest placeholderForCreatedAsset] localIdentifier];
Run Code Online (Sandbox Code Playgroud)

获取本地ID并稍后获取图像.

__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;
        }];
    }
}];
Run Code Online (Sandbox Code Playgroud)