我想知道,在Swift应用程序中,当用户从一个应用程序更改为另一个应用程序时,通常就是这样。
例如:从Google Chrome切换到Xcode等其他应用会触发此事件。
有没有办法获取应用程序切换事件,例如通过事件监视器?
答案 0 :(得分:8)
您可以在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)
}
}
答案 1 :(得分:5)
在Swift 3中,您需要为每个可选绑定使用关键字let
。此外,从userInfo字典中提取的正在运行的应用程序的类型为any
,需要进一步强制转换为NSRunningApplication
类型。
因此,Eric Aya给出的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)
}
}
(我会留下这篇文章作为对已接受答案的评论,但没有足够的代表......)