2017-04-06 62 views
0

我有一個場景,我必須在主屏幕中觸發一個計時器。當用戶轉到另一個屏幕或用戶在應用程序內漫遊時,此時在主屏幕中觸發的計時器應該正在運行並且計時器標籤必須更新。最後,用戶回到主屏幕定時器,定時器標籤應根據定時器值更新。如何實現?提前致謝。如何讓計時器在應用程序本身內保持運行狀態?

+1

使用單獨的類,並使用計時器從那裏 –

+0

您可以在後臺線程做到這一點'dispatch_async()' –

+0

我我在singleton類中存儲了定時器值。在singleton類中更新值,但當回到主屏幕時標籤沒有更新。 –

回答

0

u能在dispatch_queue_t隊列中運行:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
    dispatch_async(queue, ^{ 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      // perform on main 
      //your method for running timer: 
     }); 
    }); 
+0

感謝您的response.Its工作,但當 - (void)viewDidLoad方法調用它不工作,但定時器fire方法執行。 –

+0

我沒有得到它......你可以詳細說明你的問題..如果代碼工作,請接受它作爲答案@UdayEega –

+0

如果我們去另一個(從家)VC和回到相同的(家)VC它的工作。但在我的情況下,我從側面菜單調用家VC,以便 - (void)viewDidLoad的主頁VC正在調用。在這種情況下標籤不更新,但定時器運行。 –

0

另一種方法是把你的計時器的AppDelegate並創建一個方法在AppDelegate的啓動/停止在AppDelegate中的Timer.create協議,並調用該委託方法在定時器選擇器called.implement該協議在HomeVC

var Timer = NSTimer() 
var workTime = 0 
func startTimer() 
{ 
    self.Timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(self.countDownValue(_:)), userInfo: nil, repeats: true) 

} 
func countDownValue(dt: NSTimer) 
{ 
     self.workTime += 1 
     delegate?.updateValueofLabel(self.workTime) 
} 
0

因爲有利於讓一個後臺不支持你不能用正常的NSTimer做到這一點。然而,使用其他方法很容易實現。 在你的AppDelegate中你有兩種方法。 applicationWillResignActive和applicationDidBecomeActive。在resign方法中,您只需將當前NSDate保存到NSUserDefaults中,然後在活動方法中檢索並與當前NSDate進行比較,以獲取應用程序處於非活動狀態的時間量。

代碼示例:

func applicationWillResignActive(application: UIApplication) { 
    let date = NSDate() 
    NSUserDefaults.standardUserDefaults().setObject(date, forKey: "DateTimer") 
} 

func applicationDidBecomeActive(application: UIApplication) { 
    if let persistedDate = NSUserDefaults.standardUserDefaults().objectForKey("DateTimer") as? NSDate { 
     let difference = NSCalendar.currentCalendar().components([.Second], fromDate: persistedDate, toDate: NSDate(), options: []) 
     let differenceSeconds = difference.second 
    } 
} 

的代碼把它從這裏:Click Here

相關問題