Search code examples
swiftmacoscocoastoryboardnsimage

Unable to set Image of NSImageView using file path


I have hooked to Selection changed event of NSTableView.I need to display the selected image in the imageview

func tableViewSelectionDidChange(_ notification: Notification)
       {
        let table = notification.object as! NSTableView

        print(fileArray[table.selectedRow].path);
        img_view.image=NSImage(named: NSImage.Name(rawValue: fileArray[table.selectedRow].path))
       }

The console prints

/Users/myname/Downloads/435_v9_bc.jpg

But the imageview does not display the image.

Update 1:

 print(fileArray[table.selectedRow].path);
 img_view.image=NSImage(byReferencing: URL(string: fileArray[table.selectedRow].path)!)

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Console still prints

/Users/myname/Downloads/123_1 (1).jpeg

Solution

  • URL(string: is the wrong API, for file system paths you have to use URL(fileURLWithPath.

    img_view.image = NSImage(byReferencing: URL(fileURLWithPath: fileArray[table.selectedRow].path))
    

    However fileArray[table.selectedRow] seems to be already an URL so there is a still easier way

    img_view.image = NSImage(contentsOf: fileArray[table.selectedRow])