Search code examples
iosswiftimageuiimagepickercontrollerphotokit

How to get the asset URL of a picture taken from UIImagePicker


I'm trying to find out how to get the asset URL of an image saved to the camera roll, but I can't find much that can help me out. I've seen Objective-C examples, but I'm not experienced with it and a lot of the times they use ALAssetLibrary, which is deprecated now. All I'm doing is saving a photo, but I need to get the URL to load it into another image whose UIImageView isn't always in existence. Trying to load it to the view crashes the app.

Code:

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

Solution

  • From Apple Docs: 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.

    So iOS8 onwards use Photos API and placeholderForCreatedAsset of 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
    

    Use below for older iOS:

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