NEW: Learn SwiftData for free with my all-new book! >>

SOLVED: Adding an NSImage to NSView as a CALayer

Forums > macOS

I'm having trouble getting a disk image to be displayed in a CALayer as an NSImage in a NSView. I'm trying to build a view as a letter sized page to eventually turn into a PDF.

import Cocoa

class Page: NSView {
   func insertImage(view: NSView) -> NSView {
            Method adds a background image to the view

           let backgroundLayer = CALayer()
           backgroundLayer.bounds = CGRect(x: 0, y: 0, width: 72*8.5, height: 72*11)
           backgroundLayer.position = CGPoint(x: 0, y: 0)
           backgroundLayer.contents = NSImage(named: "/Users/Shared/background.png")
           print(backgroundLayer.contents) // <--- This is showing as nil
           backgroundLayer.contentsGravity = .resizeAspectFill
           backgroundLayer.masksToBounds = true


           return view

This is my viewcontroller.swift:

 import Cocoa

 class ViewController: NSViewController {

    let page = Page()

    override func viewDidLoad() {

        self.view.wantsLayer = true //
        self.view = page.insertImage(view: self.view)

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.



I followed the same examples I have found on SO, but it's not working for me. I threw in a print() statement to see if it's even reading the file and it is showing nil. Does this have to do with permissions or something? I'm not getting any build or runtime errors.


I have no idea why, but this is now working after moving the file to my Downloads folder. I got a promt to allow the program to access files in my Downloads folder. I thought /Users/Shared was a free-for-all and wasn't Sandboxed? That is where I've done all my development. How do I give XCode permission to read/write data in /Users/Shared?


Hacking with Swift is sponsored by Swiftable

SPONSORED An iOS conference hosted in Buenos Aires, Argentina – join us for the third edition from November 29th to December 1st!

Get your ticket

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.