2016-11-26 29 views
0

我想製作一個MenuBar唯一的應用程序,每30秒檢查一次API並根據標誌的狀態更改StatusBarIcon。我一直在關注這個教程:https://nsrover.wordpress.com/2014/10/10/creating-a-os-x-menubar-only-app/,但我只能在applicationDidFinishLaunching函數中第一次做到這一點。StatusBarIcon與類似Dropbox的行爲

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函數中將該循環異步放入?

謝謝。

+0

爲什麼**不**使用視圖控制器?你不需要在視圖中放置任何東西。 – dfd

+0

@dfd爲什麼他或她必須使用視圖控制器? –

+0

我的不好。我在考慮iOS應用程序,完全忽略鏈接中的「MenuBar」和「OS X」,而是重點關注StatusBarItem。 – dfd

回答

0

您可以運行一個時鐘來每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() { 

} 
0
var timer: DispatchSourceTimer? 

func applicationDidFinishLaunching(_ aNotification: Notification) { 
     // Insert code here to initialize your application 

    self.timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(), queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated)) 
    self.timer?.scheduleRepeating(deadline: DispatchTime.now(), interval: DispatchTimeInterval.seconds(30), leeway: DispatchTimeInterval.seconds(0)) 
    self.timer?.setEventHandler(handler: { 
     //loop body here 
     print("timer fire", separator: "", terminator: "\n") 
    }) 
    self.timer?.resume() 
}