3

I'm trying to implement the answer in iOS 8 UIImage Metadata for Objective-C in SWIFT as follows

//source: http://stackanswers.com/questions/24227578/ios-8-uiimage-metadata
func metaDataFromAssetLibrary(info: NSDictionary) {

    var assetURL = info.objectForKey(UIImagePickerControllerReferenceURL) as NSURL
    var assetLibrary = ALAssetsLibrary()
    assetLibrary.assetForURL(assetURL as NSURL, resultBlock: {
        (asset: ALAsset!) in
            var metadata: NSDictionary = asset.defaultRepresentation().metadata() as NSDictionary
            NSLog ("imageMetaData from AssetLibrary %@",metadata);

        }, failureBlock: {
            (error: NSError!) in

            NSLog("Error!")
    })

}

I'm calling it with

func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: NSDictionary!){

    // https://stackoverflow.com/questions/3088874/didfinishpickingmediawithinfo-return-nil-photo
    picker.dismissViewControllerAnimated(true, completion: nil)

    let image = info.objectForKey("UIImagePickerControllerOriginalImage") as UIImage

    PHPhotoLibrary.sharedPhotoLibrary().performChanges({
        let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
        let assetPlaceholder = createAssetRequest.placeholderForCreatedAsset
        let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection, assets: self.photosAsset)

        albumChangeRequest.addAssets([assetPlaceholder])
        }, completionHandler: {(success, error)in
            NSLog("Adding Image to Library -> %@", (success ? "Sucess":"Error!"))
            picker.dismissViewControllerAnimated(true, completion: nil)
    })
    metaDataFromAssetLibrary(info)

}

which results in a "fatal error: unexpectedly found nil while unwrapping an Optional value"

Community
  • 1
  • 1
Heavy
  • 113
  • 1
  • 7

2 Answers2

3

Try this code:

let metadata = info[UIImagePickerControllerMediaMetadata] as? NSDictionary    
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
Aditya Dharma
  • 708
  • 2
  • 8
  • 22
  • 1
    `UIImagePickerControllerMediaMetadata` only works when the image is from the camera, not the photo library. – rmaddy Jan 05 '17 at 17:41
1

If you get images from camera, you can get metadata from info[UIImagePickerControllerMediaMetadata].

HOWEVER, when you choose images from photo albums, there is no info[UIImagePickerControllerMediaMetadata] but info[UIImagePickerControllerReferenceURL]!

steveSarsawa
  • 1,559
  • 2
  • 14
  • 31
SuperBi
  • 278
  • 1
  • 2
  • 9