swift - StatusBarIcon 具有类似 Dropbox 的行为

标签 swift xcode macos swift3 macos-sierra

我想制作一个仅菜单栏的应用程序,每 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/

相关文章:

ios - 自定义导航栏被另一个导航栏隐藏,但它没有在快速 Storyboard中显示

ios - 如何使用 Swift 4 将数据从 Pop-Over subview 传递到 View Controller

ios - UIWebView 滚动到顶部时显示空白

macos - ndk-gdb 失败并显示消息 : Invalid attribute name: package

linux - -execdir 在 Linux 和 OSX 上的解释

java - Java 中是否有类似于 Swift 的强引用循环(或类似的东西)的概念?

ios - 集成自定义相机 View AVCaptureDevice

ios - 通过 URLSessionUploadTask 响应数据

iphone - Objective-C Xcode : Tableview detailitem empty

c - 如何解决 VSCODE 中链接器命令失败的编译器错误