Skip to content

Instantly share code, notes, and snippets.

@JohnSundell
Last active November 22, 2022 06:29
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JohnSundell/05f837a3f901630e65e3652945424ba5 to your computer and use it in GitHub Desktop.
Save JohnSundell/05f837a3f901630e65e3652945424ba5 to your computer and use it in GitHub Desktop.
An easy way to make code that uses UIImage cross-platform between iOS/tvOS & macOS
// Either put this in a separate file that you only include in your macOS target
// or wrap the code in #if os(macOS) / #endif
import Cocoa
// Step 1: Typealias UIImage to NSImage
typealias UIImage = NSImage
// Step 2: You might want to add these APIs that UIImage has but NSImage doesn't.
extension NSImage {
var cgImage: CGImage? {
var proposedRect = CGRect(origin: .zero, size: size)
return cgImage(forProposedRect: &proposedRect,
context: nil,
hints: nil)
}
convenience init?(named name: String) {
self.init(named: Name(name))
}
}
// Step 3: Profit - you can now make your model code that uses UIImage cross-platform!
struct User {
let name: String
let profileImage: UIImage
}
@GilesHammond
Copy link

Thank you for this John. Just a note, the extension init? is now giving a warning in Swift 4.2 - 'All paths through this function will call itself'. I'm not entirely sure of the change in 4.2, but since NSImage.Name is just a String alias, I can't see how this never recursed!

@wtpalexander
Copy link

For future visitors: removing the convenience init allows this to function as intended. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment