I'm trying to show an image from file url in IKImageView, but it only shows an empty frame. My project is in Cocoa Swift 4.2 MacOS on Xcode 10.0.
My code:
class ViewController: NSViewController {
@IBOutlet weak var imagePreView: IKImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
imagePreView.wantsLayer = true
imagePreView.setImageWith(URL(fileURLWithPath: "My_file_URL"))
imagePreView.isHidden = false
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
Am I doing something wrong or is there missing something? I have searching for hours, but I still haven't found anything usefull about IKImageView in Swift or they are all out of date, like this.
Expanding on @Willeke's comment above, the reason this didn't work was that the app (by default) is sandboxed and doesn't have access to random files on disk.
If you run into issues like this, NSImage
, IKImageView
, etc will all silently fail when trying to load an image from disk.
If you try using FileManager
or Data(contentsOf: url)
then you'll start seeing the real error, which is a permissions exception.
Turning off sandboxing does fix this, but if you're interested in learning how to grant access to read files on disk, I wrote a detailed blog post on the topic: