18

我在两种情况下使用 UIImagePickerController

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

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

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

但是当我拍摄一张新照片时,该图像尚未在照片库中,并且还没有 URL。所以,我首先需要在库中添加图像。但是,如何获取新资产的 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 ?
            ...
        }
    ];
}
4

6 回答 6

12

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

利用

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

获取本地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;
        }];
    }
}];
于 2015-09-15T08:18:25.300 回答
1

如果我们使用 ALAssetsLibrary,在 Photo Album 中保存一张图片并获取它的 URL 非常简单:

    // Get the image
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

    // Add the image in the Photo Library
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library writeImageToSavedPhotosAlbum: [image CGImage]
                              orientation: (ALAssetOrientation)[image imageOrientation]
                          completionBlock: ^(NSURL *assetURL, NSError *error)
    {
        if (error)
        {
            NSLog( @"error: %@", error );
        }
        else
        {
            NSLog( @"assetURL = %@", assetURL );
        }
    }];

但令人惊讶的是,似乎不可能用新的 PHPhotoLibrary 做同样的事情!

始终欢迎使用 PHPhotoLibrary 获得相同结果的解决方案。

于 2015-05-13T22:54:54.407 回答
1

我不喜欢这个修复,因为这可能会导致竞争状况。到目前为止,我想不出更好的解决方案。如果有人愿意,我很想听 :) 不管怎样,这里是 Rigel Chen 的回答的 Swift 版本

import Photos

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {

        var localId:String?
        let imageManager = PHPhotoLibrary.sharedPhotoLibrary()

        imageManager.performChanges({ () -> Void in

            let request = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
            localId = request.placeholderForCreatedAsset?.localIdentifier

            }, completionHandler: { (success, error) -> Void in
                dispatch_async(dispatch_get_main_queue(), { () -> Void in

                    if let localId = localId {

                        let result = PHAsset.fetchAssetsWithLocalIdentifiers([localId], options: nil)
                        let assets = result.objectsAtIndexes(NSIndexSet(indexesInRange: NSRange(location: 0, length: result.count))) as? [PHAsset] ?? []

                        if let asset = assets.first {
                            // Do something with result
                        }
                    }
                })
        })
    }
}
于 2016-03-14T10:36:10.297 回答
0

[Swift 4]这个方法可以同时处理图像和视频,享受:)

func getURL(of asset: PHAsset, completionHandler : @escaping ((_ responseURL : URL?) -> Void)) {

    if asset.mediaType == .image {
        let options: PHContentEditingInputRequestOptions = PHContentEditingInputRequestOptions()
        options.canHandleAdjustmentData = {(adjustmeta: PHAdjustmentData) -> Bool in
            return true
        }
        asset.requestContentEditingInput(with: options, completionHandler: { (contentEditingInput, info) in
            completionHandler(contentEditingInput!.fullSizeImageURL)
        })
    } else if asset.mediaType == .video {
        let options: PHVideoRequestOptions = PHVideoRequestOptions()
        options.version = .original
        PHImageManager.default().requestAVAsset(forVideo: asset, options: options, resultHandler: { (asset, audioMix, info) in
            if let urlAsset = asset as? AVURLAsset {
                let localVideoUrl = urlAsset.url
                completionHandler(localVideoUrl)
            } else {
                completionHandler(nil)
            }
        })
    }
}
于 2018-09-14T02:27:03.283 回答
0

Swift 4解决方案适用于我获取照片库中最后一张图片的网址

let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions).lastObject
PHImageManager().requestAVAsset(forVideo: fetchResult!, options: nil, resultHandler { (avurlAsset, _, _) in
    if let newObj = avurlAsset as? AVURLAsset {
        print(newObj.url)
    }
})

希望能帮助到你!

于 2018-05-20T11:49:09.767 回答
0

检索图像 URL:

- (void)processImage:(UIImage*)image type:(NSString*)mimeType forCallbackId:(NSString*)callbackId
    {
        __block NSString* localId;

        // Add it to the photo library
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];

            localId = [[assetChangeRequest placeholderForCreatedAsset] localIdentifier];
        } completionHandler:^(BOOL success, NSError *err) {
            if (!success) {
                NSLog(@"Error saving image: %@", [err localizedDescription]);
            } 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) {
                    NSURL *fileUrl = [info objectForKey:@"PHImageFileURLKey"];
                    if (fileUrl) {
                        NSLog(@"Image path: %@", [fileUrl relativePath]);
                    } else {
                        NSLog(@"Error retrieving image filePath, heres whats available: %@", info);
                    }
                }];
            }
        }];
    }
于 2018-12-05T07:17:30.030 回答