How do I create a UIImage from a CGImage in Swift?

Bill picture Bill · Jun 20, 2014 · Viewed 19.8k times · Source

I'm trying to create a UIImage from the ALAssetsGroup#posterImage method. In Objective-C, I could simply call [UIImage imageWithCGImage:group.posterImage] but in Swift, UIImage(CGImage: group.posterImage) gives me a compiler error:

Could not find an overload for 'init' that accepts the supplied arguments

What am I doing wrong?

Answer

Firo picture Firo · Jun 20, 2014

If you look at the docs in Xcode6 you will see that posterImage() returns a Unmanaged<CGImage>! (in Swift, in ObjC it returns a CGImageRef). After some investigation from the docs I found this:

When you receive an unmanaged object from an unannotated API, you should immediately convert it to a memory managed object before you work with it.

So your solution would be:

UIImage(CGImage: group.posterImage().takeUnretainedValue())