Search code examples
iosswifturlphassetphimagemanager

Getting the URL Path of an Image from device in iOS Swift


I am trying to get the image path using the PHImageManager on an actual device and not simulator. I am using photoUrl = info!["PHImageFileURLKey"] as? URL to get the url.

Now when I run my code on simulator , I get 9 key/value pairs in my info . But when I run the same code on actual device I only get 3 key/value pairs and thus I don't get photoUrl and my app crashes

Here is the code that I've been trying to implement,


var selectedPhotos : [URL] = []

 func pickerViewController(_ pickerViewController: TatsiPickerViewController, didPickAssets assets: [PHAsset])
    {

            self.selectedPhotos.removeAll()
            let imageManager = PHImageManager.default()
            let options = PHImageRequestOptions()
            options.deliveryMode = .highQualityFormat
            options.resizeMode = .exact
            options.isSynchronous = true

            let count = assets.count
            for asset : PHAsset in assets
            {
                let imageSize = CGSize(width: asset.pixelWidth,
                                       height: asset.pixelHeight)
                /* For faster performance, and maybe degraded image */
                imageManager.requestImage(for: asset,
                                          targetSize: imageSize,
                                          contentMode: .aspectFill,
                                          options: options,
                                          resultHandler:
                    {
                                            (image, info) -> Void in
                         var photoUrl : URL!
                         photoUrl = info!["PHImageFileURLKey"] as? URL
                         self.selectedPhotos.append(photoUrl)
                    })
            }
}

Solution

  • Use asset.requestContentEditingInput insted of asset.requestImagebelow to retrive image URL from PHAsset:

    func pickerViewController(_ pickerViewController: TatsiPickerViewController, didPickAssets assets: [PHAsset]){
    
        let count = assets.count
        for asset : PHAsset in assets{            
            asset.requestContentEditingInput(with: PHContentEditingInputRequestOptions()) { (eidtingInput, info) in
                if let input = eidtingInput, let photoUrl = input.fullSizeImageURL {
                    self.selectedPhotos.append(photoUrl)
                }
            }
        }
    }