Search code examples
swiftxcodemacosscreensaver

Can't load images on mac screensaver release build (it works on Xcode debug build)


I got this mac screensaver example from here.

I changed it to show image instead of textField.

The problem is this: it can show any Xcode objects such as textView. textField, Button and etc... but it cant load image on imageView. (it can load image on Xcode debug build but not on release build on mac screensavers)

Debug Build Screenshot

Release Build Screenshot . Here is my code to show image:

  let imageView = NSImageView(frame: self.frame)
  imageView.image = NSImage(named: "Image")
  imageView.layer?.backgroundColor = NSColor.red.cgColor
  imageView.backgroundColor(.red)
  addSubview(imageView)
  DispatchQueue.main.async {
      imageView.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
      self.setNeedsDisplay(imageView.frame)
  }

I am pretty sure it can not access the image file, but how can I fix this? Actually the behavior of screensaver is very weird, when I add another UI element after that ImageView, neither of them showing on the screen.

Whats wrong with macOS screensavers? (I downloaded some third party screensavers from some websites & they were black screens as well.)


Solution

  • NSImage(named:) loads from main application bundle, but your images in plug-in, so use something like the following (load from bundle containing your class)

    imageView.image = Bundle(for: type(of: self)).image(forResource: "Image")
    

    Tested with Xcode 11.2 / macOS 10.15. Images are in Assets of screensaver plug-in target.