alex
alex

Reputation: 154

Is there a way to set user desktop background wallpaper programmatically in Swift?

I haven't been able to find much documentation on this except this (Setting the Desktop background on OSX using Swift 2)

Is there a way to programmatically set users' desktop wallpaper using Swift on a macOS app? I understand I'll have to disable sandbox for it, but what can I use to programmatically set the desktop wallpaper?

Upvotes: 3

Views: 1115

Answers (1)

ChrisR
ChrisR

Reputation: 12165

your quoted link has the answer. Here is a demo:

struct ContentView: View {
    
    @State private var showFileImporter = false
    
    var body: some View {
        Button("Pick Background Image") {
            showFileImporter = true
        }
        .fileImporter(isPresented: $showFileImporter, allowedContentTypes: [.jpeg, .tiff, .png]) { result in
            switch result {
            case .failure(let error):
                print("Error selecting file \(error.localizedDescription)")
            case .success(let url):
                print("selected url = \(url)")
                setDesktopImage(url: url)
            }
            
        }
    }
    
    func setDesktopImage(url: URL) {
        do {
            if let screen = NSScreen.main {
                try NSWorkspace.shared.setDesktopImageURL(url, for: screen, options: [:])
            }
        } catch {
            print(error)
        }
    }
}

Upvotes: 4

Related Questions