2016-05-08 229 views
0

我在swift中工作,希望每分鐘運行一次函數。我想用倒數計時器更新一個標籤,剩下多少分鐘直到下一次更新。Swift:每分鐘運行一次func

我有一個基本的版本工作

if let date = newDate { 
     let formatter : NSDateFormatter = NSDateFormatter() 
     formatter.dateFormat = "HH:mm" 
     formatter.timeZone = NSTimeZone.defaultTimeZone() 

     let string : NSString = formatter.stringFromDate(date) 

     let calendar = NSCalendar.currentCalendar() 
     let comp = calendar.components([.Minute], fromDate: date) 
     let minute = comp.minute 

     let remaining : Int = 60 - minute 
     var mins = "s" 
     if remaining == 1 { 
      mins = "" 
     } 

     self.refreshInLabel.text = "Refreshes at \(string) - \n \(remaining) minute\(mins) remaining " 
    } 

當我查看應用程序的頁面被更新,但我希望它自動更新每分鐘。 我看了NSTimer,我相信它可以做到這一點(如圖所示:How to make a countdown with NSTimer on Swift),但我不能工作如何使它在一分鐘內發生火災,只有在一定的時間顯示後

編輯: 我有以下到目前爲止

override func viewDidLoad() { 
    super.viewDidLoad() 

    let calendar = NSCalendar.currentCalendar() 
    let comp = calendar.components([.Minute], fromDate: NSDate()) 
    minute = comp.minute 

    _ = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(AdoptionCentreVC.updateTimer), userInfo: nil, repeats: true) 

} 

func updateTimer() { 
    let calendar = NSCalendar.currentCalendar() 
    let comp = calendar.components([.Minute], fromDate: NSDate()) 
    let curMin = comp.minute 

    if(curMin > minute) { 
     NSLog("Changed") 
     self.minute = curMin 
    } 
} 

我想知道,如果那裏有一個更好的辦法

+0

有沒有'NSTimer'在你的代碼,所以你需要添加它。 –

+0

我知道,但我不知道要添加的時間間隔,因爲我可以找到的唯一示例顯示60秒等不到下一分鐘 –

回答

0

我建議你什麼是火NSNotification當你要開始每分鐘的FUNC。 當您收到NSNotification通話這樣的功能:

var yourTimer = NSTimer() 
func callWhenNotificationReceived(){ 
    yourFuncToFire() 
    yourTimer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: #selector(YourViewController.yourFuncToFire) , userInfo: nil, repeats: true) 
} 
-1
var TotalTime:Int = 0 
var timer: NSTimer? 


triggerCountDownTimerFor(time:Int) 

func triggerCountDownTimerFor(time:Int) 
{ 
    totalTime = time 
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: #selector(LoginViewController.updateTimer), userInfo: nil, repeats: true) 
} 

func updateTimer() 
{ 
    let date = NSDate() 
    let formatter : NSDateFormatter = NSDateFormatter() 
    formatter.dateFormat = "HH:mm" 
    formatter.timeZone = NSTimeZone.defaultTimeZone() 

    let string : NSString = formatter.stringFromDate(date) 

    let calendar = NSCalendar.currentCalendar() 
    let comp = calendar.components([.Minute], fromDate: date) 
    let minute = comp.minute 

    let remaining : Int = TotalTime - minute 
    var mins = "s" 
    if remaining == 1 { 
     mins = "" 
    } 

    print("Refreshes at \(string) - \n \(remaining) minute\(mins) remaining ") 




}