【问题标题】:Setting the Desktop background on OSX using Swift 2使用 Swift 2 在 OSX 上设置桌面背景
【发布时间】:2015-08-05 18:29:07
【问题描述】:

在介绍了 Javascript 之后,我正在尝试通过创建一些简单的工具来解决 OSX/iOS 编程问题。

但是,从跳跃开始,我就遇到了障碍。

我找到了两个应该可行的例子。

  1. https://github.com/hinderberg/ios-swift-kurs/blob/master/swift-intro/wallpaper.swift
  2. https://www.snip2code.com/Snippet/196825/Swift-shell-script-to-randomize-wallpape

这是第二个:

#!/usr/bin/env xcrun swift

import Foundation
import AppKit
let imagesDir = "/Users/david/Dropbox/Graphics/Wallpaper-HD/"
var err: NSError?

let fs = NSFileManager.defaultManager()
let filenames = fs.contentsOfDirectoryAtPath(imagesDir, error: &err) as [String]?

if let error = err {
  NSLog(error.localizedDescription)
} else {

  let imagenames = filenames!.filter { $0.hasSuffix(".jpg") || $0.hasSuffix("png") }
  let ir = Int(arc4random_uniform(UInt32(imagenames.count)))
  let imgurl = NSURL.fileURLWithPath(imagesDir + imagenames[ir])

  let workspace = NSWorkspace.sharedWorkspace()
  let screen = NSScreen.mainScreen()
  let ok : Bool = workspace.setDesktopImageURL( imgurl!, forScreen: screen!, options: nil, error: nil )

  if ok { 
    println( "New wallpaper: " + imagenames[ir] ) 
  } else { 
    println("Oops!")
  }
}

这在 XCode 7 beta 3 中不起作用。

希望减少到要领,我到达:

#!/usr/bin/env xcrun swift
import Foundation
import AppKit
let imagesDir = "/Users/josh/Downloads/"
let singleImage = "/Users/josh/Downloads/xlarge.png"


let imgurl = NSURL.fileURLWithPath(singleImage)

let workspace = NSWorkspace.sharedWorkspace()
let screen = NSScreen.mainScreen()
let ok : Bool = workspace.setDesktopImageURL( imgurl, forScreen: screen!, options: nil, error: nil )

if ok {
    print( "New wallpaper set!" )
} else {
    print("Oops!")
}

并保存为文件wallpaper.swift

执行时,错误是:

./wallpaper.swift:17:49: error: extra argument 'error' in call
let ok : Bool = workspace.setDesktopImageURL( imgurl, forScreen: screen!, options: nil, error: nil )

现在我完全被困住了...... 我试过参考NSWorkspaceNSScreen 文档以及在操场上跑步,但这超出了我目前的技能。

删除它抱怨的额外参数(错误:nil)只会给出不同的错误:

./wallpaper.swift:13:31: error: cannot invoke 'setDesktopImageURL' with an argument list of type '(NSURL, forScreen: NSScreen?, options: nil)'
let ok : Bool = workspace.setDesktopImageURL( imgurl, forScreen: screen, options: nil )

代码在哪里失败,我如何理解如何使其正常工作?

【问题讨论】:

  • 不熟悉waith OSX函数,但是从错误来看,你有没有试过从“workspace.setDesktopImageURL”函数中去掉“error: nil”?
  • 是的,返回的错误是./wallpaper3.swift:13:31: error: cannot invoke 'setDesktopImageURL' with an argument list of type '(NSURL, forScreen: NSScreen?, options: nil)' let ok : Bool = workspace.setDesktopImageURL( imgurl, forScreen: screen, options: nil )。 “额外参数”错误似乎是“它坏了,自己弄清楚”错误之一。
  • 在 Xcode 中,使用 ALT+CLICK 来查看对象的类型。如果您在.setDesktopImageURL 上执行 ALT+CLICK,Xcode 将显示此方法的类型和签名。然后您将看到必须使用的正确参数(文档可能未更新)。
  • @EricD。这很方便,谢谢。我点击了.setDesktopImageURL,它说没有快速帮助,但是当我点击命令时,它把我带到了声明处(也很方便,不会想到这一点)。那里的代码是 func setDesktopImageURL(url: NSURL, forScreen screen: NSScreen, options: [String : AnyObject]) throws 。这对错误的位置更有意义吗?

标签: macos swift cocoa swift2


【解决方案1】:

在您的示例中,您将 nil 作为 options 传递给该方法。

我猜它以前可以工作,但现在在 cmets 中您显示了当前方法签名:

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

我们看到options 应该是一个非可选字典。

这意味着您不能再将nil 用于options 参数:如果您没有选项,只需传递一个空字典。

另外,现在在 Swift 2 中,这个方法不再返回 Bool,而是抛出。

意思是你必须和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)
}

【讨论】:

  • 这段代码运行良好,解释清楚。谢谢你。我还有很多东西要学。
  • 像魅力一样工作!知道如何在多个空间上设置桌面图片吗?
  • @Hexagons 不幸的是,没有相应的 API。一些 hacks 过去可以工作,但现在显然不行了。
【解决方案2】:

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)
}

【讨论】:

    【解决方案3】:

    对于我们这些使用 Xamarin Mac 的人,可以这样实现:

    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);
    

    【讨论】:

      【解决方案4】:

      Swift 5.x 的更新版本:

      do {
          let imageURL = URL(fileURLWithPath: "/path/to/image")
          if let screen = NSScreen.main {
              try NSWorkspace.shared.setDesktopImageURL(imageURL, for: screen, options: [:])
          }
      } catch {
          print(error)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-02
        • 1970-01-01
        • 1970-01-01
        • 2021-01-14
        • 1970-01-01
        相关资源
        最近更新 更多