我想从Swift应用程序内部知道用户何时从一个应用程序更改为另一个应用程序。
例如:从Google Chrome浏览器切换到其他应用(例如Xcode)将触发此事件。
有没有办法通过事件监视器来接收应用程序切换事件?
您可以在NSWorkspace.sharedWorkspace().notificationCenter观察NSWorkspaceDidActivateApplicationNotification钥匙时添加观察者。您将选择器指向您的一种方法,然后从userInfo字典中获取信息。
NSWorkspace.sharedWorkspace().notificationCenter
NSWorkspaceDidActivateApplicationNotification
userInfo
AppDelegate中的简单示例:
斯威夫特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) } }
迅捷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) } }