这个帖子有点旧,但很有帮助。我根据 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 的新手。我不知道以上是否有效,但它对我有用。我从 How to create a minimal daemon process in a swift 2 command line tool? 和 Swift 3 NSNotificationCenter Keyboardwillshow/hide 等众多其他人那里得到了帮助。
斯威夫特 4:
NSWorkspace.shared.notificationCenter.addObserver(self, // HERE, shared
selector: #selector(printMe(_:)),
name: NSWorkspace.didActivateApplicationNotification, // HERE
object:nil)
编辑 (Swift 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()