Search code examples
iosswiftuiimageuiimagepickercontroller

How to get UIImage metadata from UIImagePickerController in swift ? like ".location"


Here is code what i tried

public func imagePickerController(_ picker: UIImagePickerController,
                                  didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
    guard let image = info[.editedImage] as? UIImage else {
        return self.pickerController(picker, didSelect: nil)
    }
    if let asset: PHAsset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset {
        print("Asset: \(asset)")
        print("Creation Data \(String(describing: asset.creationDate))")
        print("Location: \(String(describing: asset.location))")
        print("burstIdentifier: \(String(describing: asset.burstIdentifier))")
        print("burstSelectionTypes: \(String(describing: asset.burstSelectionTypes))")
        print("duration: \(String(describing: asset.duration))")
        print("mediaSubtypes: \(String(describing: asset.mediaSubtypes))")
        print("mediaType: \(String(describing: asset.mediaType))")
        print("pixelHeight: \(String(describing: asset.pixelHeight))")
        print("pixelWidth: \(String(describing: asset.pixelWidth))")
        print("sourceType: \(String(describing: asset.sourceType))")
    } else {
        print("Asset: nil")
    }
    self.pickerController(picker, didSelect: image)
}

Note: i also tried with PHAsset, but it's always return nil. Also find some suggestions but that all are deprecated.


Solution

  • You need to store the image in PHAsset first then you will get the asset object.

    if let originalImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            self.getAssetAfterStoreImage(image: originalImage) { (assetInstance) in
                //asset
                print(assetInstance)
            }
        }
    }
    
    func getAssetAfterStoreImage(image:UIImage,completion:@escaping (PHAsset) -> Void){
        
        PHPhotoLibrary.shared().performChanges({
            
            PHAssetChangeRequest.creationRequestForAsset(from: image)
        }) { saved, error in
            
            if saved {
                let fetchOptions = PHFetchOptions()
                fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
                
                // After uploading we fetch the PHAsset for most recent video and then get its current location url
                if let fetchResult = PHAsset.fetchAssets(with:.image, options: fetchOptions).lastObject{
                    completion(fetchResult)
                }
            }
        }
    }
    

    Please let me know if any queries.