在介绍了Javascript之后,我试图通过创建一些简单的工具来解决OSX/iOS编程问题。
然而,从一开始我就遇到了障碍。
我找到了两个应该有用的例子。
- https://github.com/hinderberg/ios-swift-kurs/blob/master/swift-intro/wallpaper.swift
- 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 )
现在我完全卡住了...我试着参考NSWorkspace和NSSscreen文档,也试着在操场上跑,但这超出了我目前的技能。
删除它所抱怨的额外参数(错误: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 )
代码在哪里失败了,我如何才能理解如何使它正常工作?
4条答案
按热度按时间w9apscun1#
在您的示例中,将
nil
作为options
传递给方法。我猜它以前是有效的,但是现在在注解中显示了当前的方法签名:
我们看到
options
应该是一个非可选字典。这意味着您不能再对
options
参数使用nil
:如果没有其他选项,只需传递一个空的Dictionary。而且,现在在Swift 2中,这个方法不再返回Bool,而是抛出。
这意味着您必须将其与
do try catch
一起使用:tvz2xvvm2#
Swift 3的更新示例:
9vw9lbht3#
对于我们这些使用Xamarin Mac的人来说,这可以这样实现:
bihw5rsg4#
Swift 5.x的更新版本: