24

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?

Firo
  • 15,448
  • 3
  • 54
  • 74
Bill
  • 44,502
  • 24
  • 122
  • 213
  • The real problem here is the "could not find an overload" message is not very informative. I suggest you file an enhancement request about that. Swift could do a lot better with its error messages. – matt Jun 20 '14 at 04:31
  • @Fattie Check the date: this question was about the original version of Swift, not the current version. And there was no crash - it was a compiler error. – Bill Feb 21 '23 at 19:40

4 Answers4

32

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())
Firo
  • 15,448
  • 3
  • 54
  • 74
  • 1
    That doesn't help, but the error message I got from that code did: "no method for `() -> Unmanaged!`". So `posterImage` is a `func` rather than a property. Adding parens after posterImage did the trick. – Bill Jun 20 '14 at 11:00
12

Update for 2023 syntax:

someImage = UIImage(cgImage: someCGImage)

A typical example is taking the image from a CALayer:

someImage = UIImage(cgImage: donorLayer.contents as! CGImage)

Are you sure group.posterImage is not an optional?

have you tried

var img = UIImage(CGImage: group.posterImage!) // 2010s syntax
Fattie
  • 27,874
  • 70
  • 431
  • 719
Albert James Teddy
  • 1,336
  • 1
  • 13
  • 24
3

Here's an example that should work for you with Xcode 8.3:

    let frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 1920, height: 1080))
    let cgImage = CIContext().createCGImage(CIImage(color: .black()), from: frame)!
    let uiImage = UIImage(cgImage: cgImage)
Jeremy Huddleston Sequoia
  • 22,938
  • 5
  • 78
  • 86
2

Use init with CGIImage:

UIImage.init(CGImage: group.posterImage, scale: self.scale, orientation: .UpMirrored)
Pichirichi
  • 1,440
  • 11
  • 15