Swift Mac - File doesn't exist loading image from same folder as main source file

56 Views Asked by At

I've been struggling with this for a bit, I can't seem to load an image(I've tried absolute/relative paths and different folders). The app is to set the wallpaper using an image. Also for some reason the image file doesn't show up in Appcode but it does in the terminal.

import Cocoa

let screens = NSScreen.screens[0]
let imgurl = NSURL.init(fileURLWithPath: "cheese.jpg")
try! NSWorkspace().setDesktopImageURL(imgurl as URL, for: screens)

wallpapersetter/main.swift:32: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=4 "The file doesn’t exist."

enter image description here

I did some searching and thought it might be a sandboxing issue but sandboxing has been disabled when i tried it in xcode and it still didn't work. It's also quite difficult to find info as the majority of swift questions are about IOS

1

There are 1 best solutions below

0
vadian On

URL doesn't provide a current directory like other programming languages

The most relative API Foundation supports is

let url = URL(string: "wallpapersetter/wallpapersetter/cheese.jpg",
        relativeTo: try! FileManager.default.url(for: .documentDirectory,
                                                 in: .userDomainMask,
                                                 appropriateFor: nil,
                                                 create: false))

for: .documentDirectory, in: .userDomainMask points to the Documents directory of the current user. If the project is sandboxed it points to the Documents directory in the application container.

Another way is to put the resource into the application bundle (if there is one). Bundle provides (relative) APIs to access items inside the bundle.