Getting images from the AppKit pasteboard
Jun 3, 2022 ·
In this post, we’ll take a look at how to fetch images from the AppKit NSPasteboard
, which behaves a bit differently than the UIKit UIPasteboard
.
Unlike UIPasteboard
, NSPasteboard
has no convenient way to fetch images. Instead, you use readObjects(forClasses:)
and cast the result to an NSImage
array.
You can make NSPasteboard
behave more like UIPasteboard
by adding these properties:
import AppKit
extension NSPasteboard {
var image: ImageRepresentable? {
images?.first
}
var images: [ImageRepresentable]? {
readObjects(forClasses: [NSImage.self]) as? [NSImage]
}
}
This lets you use images
to get all images in the pasteboard, and image
to fetch the first. If the pasteboard doesn’t contain any images, these properties will return nil
.
Discussions & More
If you found this interesting, please share your thoughts on Bluesky and Mastodon. Make sure to follow to be notified when new content is published.