如何获取从 UIImagePicker 拍摄的图片的资产 URL

Posted

技术标签:

【中文标题】如何获取从 UIImagePicker 拍摄的图片的资产 URL【英文标题】:How to get the asset URL of a picture taken from UIImagePicker 【发布时间】:2015-12-27 05:54:33 【问题描述】:

我正在尝试了解如何获取保存到相机胶卷的图像的资产 URL,但找不到太多可以帮助我的信息。我看过 Objective-C 的例子,但我对它没有经验,而且很多时候他们使用 ALAssetLibrary,现在已弃用。我所做的只是保存一张照片,但我需要获取 URL 以将其加载到另一个 UIImageView 并不总是存在的图像中。尝试将其加载到视图会使应用程序崩溃。

代码:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: AnyObject]) 
    imagePicker.dismissViewControllerAnimated(true, completion: nil)
    imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    UIImageWriteToSavedPhotosAlbum((info[UIImagePickerControllerOriginalImage] as? UIImage)!, nil, nil, nil)
    if let detail = self.detailItem 
        print(info.values)
        // ### Where I need to have the image URL ###
        //detail.thumbnail = info[UIImagePickerControllerReferenceURL] as! String
    

【问题讨论】:

【参考方案1】:

来自 Apple 文档:The Assets Library framework is deprecated as of ios 9.0. Instead, use the Photos framework instead, which in iOS 8.0 and later provides more features and better performance for working with a user’s photo library.

所以 iOS8 以后使用 Photos API 和 placeholderForCreatedAsset 的 PHAssetChangeRequest

    phphotoLibrary.sharedPhotoLibrary().performChanges(
    let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(info[UIImagePickerControllerOriginalImage])
    let assetPlaceholder = assetRequest.placeholderForCreatedAsset
, completionHandler:  success, error in
    // completion handling
)

// I have not tested but this should work

以下用于旧版 iOS:

func writeImageToSavedPhotosAlbum(_ imageRef: CGImage!,
                         metadata metadata: [NSObject : AnyObject]!,
                  completionBlock completionBlock: ALAssetsLibraryWriteImageCompletionBlock!)

【讨论】:

以上是关于如何获取从 UIImagePicker 拍摄的图片的资产 URL的主要内容,如果未能解决你的问题,请参考以下文章

裁剪 UIImagePicker 并输出到 CollectionView 单元格

测试 UIImagePicker

从照片库中获取图像名称

从 uiimagepicker 上传 uiwebview 中的图像

如何获取拍摄照片的创建日期?

在 iPhone 上的 UIImagePicker 中重新调整图像大小