Setting the Desktop background on OSX using Swift 2

前端 未结 3 1862
耶瑟儿~
耶瑟儿~ 2020-12-28 12:21

After an introduction to Javascript, I\'m trying to tackle OSX/iOS programming by creating some simple tools to scratch my own itches.

However, right from the jump I

相关标签:
3条回答
  • 2020-12-28 12:32

    In your example you're passing nil as options to the method.

    I guess it worked before but now in the comments you showed the current method signature:

    (url: NSURL, forScreen screen: NSScreen, options: [String : AnyObject]) throws
    

    We see that options should be a non-Optional Dictionary.

    It means you can't use nil anymore for the options parameter: if you don't have options, just pass an empty Dictionary.

    Also, now in Swift 2, this method doesn't return a Bool anymore, it throws.

    Meaning you have to use it with do try catch:

    do {
        let imgurl = NSURL.fileURLWithPath(singleImage)
        let workspace = NSWorkspace.sharedWorkspace()
        if let screen = NSScreen.mainScreen()  {
            try workspace.setDesktopImageURL(imgurl, forScreen: screen, options: [:])
        }
    } catch {
        print(error)
    }
    
    0 讨论(0)
  • 2020-12-28 12:41

    For those of us using Xamarin Mac, this can be achieved like so:

    string filepath = "/Users/you/Desktop/sweet-wallpaper.jpg";
    
    var workspace = NSWorkspace.SharedWorkspace;
    var screen = NSScreen.MainScreen;
    
    NSUrl url = NSUrl.FromFilename(filepath);
    NSDictionary options = new NSDictionary();
    NSError errorContainer = new NSError();
    
    workspace.SetDesktopImageUrl(url, NSScreen.MainScreen, options, errorContainer);
    
    0 讨论(0)
  • 2020-12-28 12:46

    Updated example for Swift 3:

    do {
       let imgurl = NSURL.fileURL(withPath: singleImage)
       let workspace = NSWorkspace.shared()
       if let screen = NSScreen.main()  {
           try workspace.setDesktopImageURL(imgurl, for: screen, options: [:])
       }
    } catch {
       print(error)
    }
    
    0 讨论(0)
提交回复
热议问题