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

时间:2015-05-12 16:48:58

标签: url ios8 phphotolibrary

我在两种情况下使用UIImagePickerController

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

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

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

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

5 个答案:

答案 0 :(得分:10)

我没有找到获取网址的方法,但也许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;
        }];
    }
}];

答案 1 :(得分:1)

如果我们使用ALAssetsLibrary,将图片保存在相册中并获取其网址非常简单:

    // 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获得相同结果的解决方案。

答案 2 :(得分:1)

我不喜欢这个修复,因为这可能导致竞争条件。到目前为止,我无法想到更好的解决方案。如果有人,我很乐意听到它:) 无论哪种方式,这里都是一个Swift版本的Rigel Chen的回答

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
                        }
                    }
                })
        })
    }
}

答案 3 :(得分: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)
    }
})

希望它有所帮助!

答案 4 :(得分:0)

获取图片网址:

IF OBJECT_ID('dbo.Table1', 'U') IS NOT NULL 
    DROP TABLE dbo.Table1; 

CREATE TABLE Table1 
( 
    ID INT, 
    FirstName VARCHAR(50) 
)

INSERT INTO Table1 (ID, FirstName) 
VALUES 
    (1, 'Bob'), 
    (2, 'Peter'), 
    (3, 'Joe');

IF OBJECT_ID('dbo.Table2', 'U') IS NOT NULL 
    DROP TABLE dbo.Table2; 

CREATE TABLE Table2 
( 
    ID INT, 
    SecondName VARCHAR(50) 
)

INSERT INTO Table2 (ID, SecondName) 
VALUES 
    (1, 'Meggy'), 
    (2, 'Paula'), 
    (3, 'Stella');

SELECT * 
FROM 
    Table1 
WHERE 
    FirstName NOT IN (SELECT FirstName FROM Table2)