How to retrieve PHAsset from UIImagePickerController

Viewed 10715

I'm trying to retrieve a PHAsset however PHAsset.fetchAssets(withALAssetURLs:options:) is deprecated from iOS 8 so how can I properly retrieve a PHAsset?

4 Answers

I had the same the issue, first check permissions and request access:

let status = PHPhotoLibrary.authorizationStatus()

if status == .notDetermined  {
    PHPhotoLibrary.requestAuthorization({status in

    })
}

Just hook that up to whatever triggers your UIImagePickerController. The delegate call should now include the PHAsset in the userInfo.

guard let asset = info[UIImagePickerControllerPHAsset] as? PHAsset

Here is my solution:

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

        if #available(iOS 11.0, *) {
               let asset = info[UIImagePickerControllerPHAsset]

        } else {
               if let assetURL = info[UIImagePickerControllerReferenceURL] as? URL {
               let result = PHAsset.fetchAssets(withALAssetURLs: [assetURL], options: nil)
               let asset = result.firstObject
               }
       }
}

The PHAsset will not appear in the didFinishPickingMediaWithInfo: info result unless the user has authorized, which did not happen for me just by presenting the picker. I added this in the Coordinator init():

            let status = PHPhotoLibrary.authorizationStatus()

            if status == .notDetermined  {
                PHPhotoLibrary.requestAuthorization({status in

                })
            }
Related