该线程有点旧,但非常有帮助。我根据 Marco 的帖子和 uchuugaka 的答案做了一些研究。以下是结果。
// swift 3.0
// compile: xcrun -sdk macosx swiftc -framework Cocoa foo.swift -o foo
// run: ./foo
import Cocoa
class MyObserver: NSObject {
override init() {
super.init()
NSWorkspace.shared().notificationCenter.addObserver(self,
selector: #selector(printMe(_:)),
name: NSNotification.Name.NSWorkspaceDidActivateApplication,
object:nil)
}
dynamic private func printMe(_ notification: NSNotification) {
let app = notification.userInfo!["NSWorkspaceApplicationKey"] as! NSRunningApplication
print(app.localizedName!)
}
}
let observer = MyObserver()
RunLoop.main.run()
我是 Cocoa 和 Swift 的新手。我不知道上面的方法是否有效,但它对我有用。我得到了帮助如何在 swift 2 命令行工具中创建最小守护进程? https://stackoverflow.com/questions/31469532/how-to-create-a-minimal-daemon-process-in-a-swift-2-command-line-tool and Swift 3 NSNotificationCenter 键盘将显示/隐藏 https://stackoverflow.com/questions/37825327/swift-3-nsnotificationcenter-keyboardwillshow-hide等等。
Swift 4:
NSWorkspace.shared.notificationCenter.addObserver(self, // HERE, shared
selector: #selector(printMe(_:)),
name: NSWorkspace.didActivateApplicationNotification, // HERE
object:nil)
编辑(斯威夫特 4)
编译器说printMe
函数必须是@objc
。 (我不知道什么意思,但是当我在前面添加时它起作用了@objc
在该行的开头。这是轻松复制粘贴的完整代码。
// swift 4.0
// compile: xcrun -sdk macosx swiftc -framework Cocoa foo.swift -o foo
// run: ./foo
import Cocoa
class MyObserver: NSObject {
override init() {
super.init()
NSWorkspace.shared.notificationCenter.addObserver(self,
selector: #selector(printMe(_:)),
name: NSWorkspace.didActivateApplicationNotification,
object:nil)
}
@objc dynamic private func printMe(_ notification: NSNotification) {
let app = notification.userInfo!["NSWorkspaceApplicationKey"] as! NSRunningApplication
print(app.localizedName!)
}
}
let observer = MyObserver()
RunLoop.main.run()