I'm currently creating a tiny open source app to preview an inside the new Touch Bar.
I have a window with a drag n drop view to receive images via it's URL. And a IB Touch Bar with a NSImageView inside a TouchBarView.
interface builder structure (screenshot)
This is working in my MainViewController
to show the image in the window:
extension ViewController: DropDestinationViewDelegate {
func processImageURLs(_ urls: [URL]) {
for (_,url) in urls.enumerated() {
// pass URL to Window Controller
let windowController = WindowController()
windowController.showImageInTouchBar(url)
// create the image from the content URL
if let image = NSImage(contentsOf:url) {
imagePreviewView.image = image
}
}
}
}
As you can see I use a delegate to listen to the drag n drop events to get the image URL. Now I want to use the image/URL to show the same image inside the Touch Bar. I've created the Touch Bar with Interface Builder and I'm passing the image-url to the WindowController
.
In my WindowController
I try to handle the image like this:
class WindowController: NSWindowController {
@IBOutlet var touchBarImageView: NSImageView!
override func windowDidLoad() {
super.windowDidLoad()
}
func showImageInTouchBar(_ url: URL) {
print(url)
if let touchbarImage = NSImage(contentsOf:url) {
touchBarImageView.image = touchbarImage
}
}
}
I'm receiving the correct URL with print(url)
, but when I try to create the image again, the app is crashing with the following message:
fatal error: unexpectedly found nil while unwrapping an Optional value
I created a pull request with a fix.
Your problem was that you was creating a new WindowController and using this as reference instead using the controller created and used by NSWindow.
Result: