Martin Q Martin Q - 7 months ago 51
Swift Question

How do you use a button click function to convert an PHAsset to a UIImage

Ok, so i've been at this for a while and I just can't seem to solve it.

I have an ImagePicker which bundles images into PHAssest. It's from https://github.com/hyperoslo/ImagePicker

When an image is selected, the done button is activated. I have a UIImageView which when i press the

func doneButtonDidPress(images: [UIImage])
, would convert the PHAsset into a UIImage and load it into the ImageView. Currently, this is my code which doesn't work:

// CONVERT PHASSET TO UIIMAGE
func getAsset(asset: PHAsset) -> UIImage {
let manager = PHImageManager.defaultManager()
let option = PHImageRequestOptions()
var image = UIImage()
option.synchronous = true
manager.requestImageForAsset(asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .AspectFit, options: option, resultHandler: {(result, info)->Void in
image = result!
})
return image
}




func doneButtonDidPress(images: [UIImage]) {



self.imagePickerController.dismissViewControllerAnimated(true, completion: nil)
var selectedImg = imagePickerController.stack.assets

getAsset(selectedImg)
self.SelectedImageView.image = UIImage(named: selectedImg)



}


Which flags with errors. Can anyone help me here?! Thankyou

Answer

I am getting UIImage from PHAsset like :

func getAsset(asset: PHAsset) -> UIImage {
var image = UIImage()
let imgManager = PHImageManager.defaultManager()
            let requestOptions = PHImageRequestOptions()
            requestOptions.synchronous = true
            imgManager.requestImageForAsset(asset, targetSize: CGSizeMake(300.0, 300.0), contentMode: PHImageContentMode.AspectFit, options: requestOptions, resultHandler: { (img, _) in
                image = img
            })
return image
}

This code is tested & currently working in my application.

Done Button method should be like :

func doneButtonDidPress(image: [UIImage]) {
self.imagePickerController.dismissViewControllerAnimated(true, completion: nil)
var selectedImg = imagePickerController.stack.assets.first
self.selectedImageView.image = getAsset(selectedImg)
}