我想知道,从一个Swift应用程序中,当用户从一个应用程序更改为另一个应用程序时,一般情况下.
例如:从Google Chrome切换到Xcode等其他应用会触发此事件.
有没有办法获取应用程序切换事件,例如通过事件监视器?
您可以在NSWorkspace.sharedWorkspace().notificationCenter上添加观察者,以查看NSWorkspaceDidActivateApplicationNotification密钥.您将选择器指向您的一个方法,并从userInfo字典中获取信息.
原文链接:https://www.f2er.com/swift/320016.htmlAppDelegate中的简单示例:
斯威夫特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) } }