2015-10-13 63 views
0

我想檢查我的應用程序可以保留多少次後臺。所以我設法它使用此代碼函數不能從NSTimer選擇器在swift中調用(在模擬器中工作,但不在設備中)

func applicationDidEnterBackground(application: UIApplication) { 
    print("entered in background") 
    let timer = NSTimer.scheduledTimerWithTimeInterval(60 * 5, target: self, selector: "update", userInfo: nil, repeats: true) 
    timer.fire() 
} 

我更新功能

func update(){ 
    print("func call") 
} 

所有這些代碼工作的模擬器,但每當我在設備上運行我的項目也沒有調用這個函數。
此功能也適用於在前臺應用程序檢查正確的計時器工作或不工作時調用。
我正在使用swift 2.0。
可能應用所有解決方案,但沒有成功。

編輯:
同樣使用這個代碼

NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector(update()), userInfo: nil, repeats: true) 

但它調用函數只有第一次

回答

1

當您的應用程序進入後臺時,將無法保證計時器將會啓動。您可能需要一段時間才能讓iOS停止任務,但有時您無法獲取任何內容,例如設備鎖定時。 如果你想在後臺運行的東西,你需要看看Background Mode Execution

0

您是否嘗試過聲明喜歡你的方法,以便:

func update(sender: NSTimer?) -> Void { 
    print("func call") 
} 

,使確定你這樣稱呼它(注意分號:

func applicationDidEnterBackground(application: UIApplication) { 
    print("entered in background") 
    let timer = NSTimer.scheduledTimerWithTimeInterval(60 * 5, target: self, selector: "update:", userInfo: nil, repeats: true) 
    timer.fire() 
} 
+1

已經嘗試過,但沒有成功....它只是打印「進入後臺」,但不再打印功能說明 –

+0

哦,我只是注意到當你的應用程序進入後臺時你正在調用這個...你爲什麼要這樣做?嘗試在appDidEnterForeground,看看它是否有效 – bsarrazin

+0

這種方法不存在。 applicationWillEnterForeground存在。但我想檢查應用程序可以保留在後臺有多少時間....所以我已經使用這個 –

相關問題