我想制作一个仅菜单栏的应用程序,每 30 秒检查一次 API,并根据标志的状态更改 StatusBarIcon。我一直在关注本教程:https://nsrover.wordpress.com/2014/10/10/creating-a-os-x-menubar-only-app/但我只能在 applicationDidFinishLaunching
函数中第一次执行此操作。
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
statusBarItem = NSStatusBar.system().statusItem(withLength: NSSquareStatusItemLength)
statusBarItem?.image = #imageLiteral(resourceName: "locked")
self.fetchOccupied { (occupied) in
if (occupied) {
self.statusBarItem?.image = #imageLiteral(resourceName: "locked")
} else {
self.statusBarItem?.image = #imageLiteral(resourceName: "unlocked")
}
}
}
之后,就像我说的,我想每 30 秒再次检查一次,而不必单击 StatusBarItem,但我无法将循环放入该函数中,因为那样应用程序将永远不会启动。
我不知道将循环放在哪里,因为我没有主 ViewController 或任何东西。我只有 AppDelegate 类和 XIB 文件。
在哪里可以创建放置循环的函数?也许我可以将该循环异步放入 applicationDidFinishLaunching
函数中?
谢谢。
最佳答案
您只需运行一个时钟即可每 30 秒收到一次通知。
func applicationDidFinishLaunching(_ aNotification: Notification) {
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(updateClock), userInfo: nil, repeats: true)
}
func updateClock() {
let date = NSDate()
let calendar = NSCalendar.current
let components = calendar.dateComponents([.second],from:date as Date) as NSDateComponents
if components.second == 0 || components.second == 30 {
makeStatusMenu()
}
}
func makeStatusMenu() {
}
关于swift - StatusBarIcon 具有类似 Dropbox 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40820444/