通过UIImagepickerController在swift中获取元数据

时间:2014-10-15 20:06:49

标签: ios swift

我正在尝试在iOS 8 UIImage Metadata中为SWIFT中的Objective-C实现答案,如下所示

//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!")
    })

}

我用

来称呼它
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)

}

导致“致命错误:在解包可选值时意外发现nil”

2 个答案:

答案 0 :(得分:3)

试试这段代码:

let metadata = info[UIImagePickerControllerMediaMetadata] as? NSDictionary    
let image = info[UIImagePickerControllerOriginalImage] as? UIImage

答案 1 :(得分:0)

如果您从相机获取图像,则可以从info [UIImagePickerControllerMediaMetadata]获取元数据。

但是,当您从相册中选择图片时,没有信息[UIImagePickerControllerMediaMetadata],但是信息[UIImagePickerControllerReferenceURL]!