我希望能够在Swift应用程序内部了解用户何时通常从一个应用程序切换到另一个应用程序。
例如:从Google Chrome切换到其他应用程序(如Xcode)将触发此事件。
是否有任何方法可以通过事件监视器等方式捕获应用程序切换事件?
您可以在 NSWorkspace.sharedWorkspace().notificationCenter
上添加一个观察者,观察 NSWorkspaceDidActivateApplicationNotification
键的变化。将选择器指向您的其中一个方法,并从 userInfo
字典中获取信息。
在AppDelegate中有一个简单的示例:
Swift 2.2
func applicationDidFinishLaunching(notification: NSNotification) {
NSWorkspace.sharedWorkspace().notificationCenter.addObserver(self,
selector: #selector(activated),
name: NSWorkspaceDidActivateApplicationNotification,
object: nil)
}
func activated(notification: NSNotification) {
if let info = notification.userInfo,
app = info[NSWorkspaceApplicationKey],
name = app.localizedName {
print(name)
}
}
Swift 3
func applicationDidFinishLaunching(_ aNotification: Notification) {
NSWorkspace.shared().notificationCenter.addObserver(self,
selector: #selector(activated(_:)),
name: NSNotification.Name.NSWorkspaceDidActivateApplication,
object: nil)
}
func activated(_ notification: NSNotification) {
if let info = notification.userInfo,
let app = info[NSWorkspaceApplicationKey] as? NSRunningApplication,
let name = app.localizedName
{
print(name)
}
}
let
。此外,从userInfo字典中提取的运行应用程序属于any
类型,需要进一步转换为NSRunningApplication
类型。func applicationDidFinishLaunching(_ aNotification: Notification) {
NSWorkspace.shared().notificationCenter.addObserver(self,
selector: #selector(activated),
name: NSNotification.Name.NSWorkspaceDidActivateApplication,
object: nil)
}
func activated(notification: NSNotification) {
if let info = notification.userInfo,
let app = info[NSWorkspaceApplicationKey] as? NSRunningApplication,
let name = app.localizedName {
print(name)
}
}