I'm trying to create an image from the contents of (all subviews) an NSImageView
and save it to disk on a Mac. Right now the step of writing it to disk is failing. As I step through the code in the debugger, I notice that imageData
doesn't appear to be created properly. The Variables View shows imageData
's value as some
and when I look deeper the field backing.bytes
is nil
.
My guess is this line:
let imageData: Data! = rep!.representation(using: NSBitmapImageRep.FileType.png, properties: [:])
is failing. Here is the full code I am using:
class ExportableImageView: NSImageView {
func saveToDisk() {
let rep: NSBitmapImageRep! = self.bitmapImageRepForCachingDisplay(in: self.bounds)
self.cacheDisplay(in: self.bounds, to: rep!)
let imageData: Data! = rep!.representation(using: NSBitmapImageRep.FileType.png, properties: [:])
let paths = NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true)
let desktopPath = URL.init(string: paths[0])
let savePath = desktopPath?.appendingPathComponent("test.png")
do {
try imageData!.write(to: savePath!, options: .atomic)
}
catch {
print("save error")
}
}
/* Other stuff */
}
Any ideas why this would be failing? Thanks.