2014-12-29 53 views
5

我ViewController.swift暫停計時器時應用程序是在後臺狀態斯威夫特

func startTimer() { 
timer = NSTimer().scheduleTimerWithTimerInvterval(1.0,target: self,selctor: Selector("couting"),userinfo: nil, repeats: true) 
} 
func pauseTimer() { 
timer.invalidate() 
println("pausing timer") 
} 

,這是appDelegate.swift

func applicateWillResignActive(application: UIApplication) { 
viewController().pauseTimer() 
println("closing app") 
} 

正在打印暫停定時器和關閉應用程序但是當我打開我再次看到它永不停歇。我如何正確地做到這一點?

+0

試試這個控制,希望這會對你有幫助。 https://www.cocoacontrols.com/controls/game-timer –

+0

,當應用程序處於後臺狀態時不會暫停 – user528432

回答

22

你必須設置一個觀察者監聽應用程序何時進入後臺。在ViewController的viewDidLoad()方法中添加下面的代碼行。

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("myObserverMethod:"), name:UIApplicationDidEnterBackgroundNotification, object: nil) 

添加以下函數以接收通知。

func myObserverMethod(notification : NSNotification) { 
    println("Observer method called") 

    //You may call your action method here, when the application did enter background. 
    //ie., self.pauseTimer() in your case. 
} 

快樂編碼!在斯威夫特3

+0

這是完美的蘇雷什,我必須創建一個新的觀察員,當用戶回來,所以我可以恢復計時器? – user528432

+0

是的,你必須創建另一個觀察者來監聽UIApplicationDidBecomeActiveNotification,同樣你也可以像上面指定的那樣調用觀察者內部的動作。 – Suresh

+0

太棒了!當用戶再次進入然後恢復計時器時,我創建了相同的func。它的工作很好(y) – user528432

0

您正在創建一個新的對象,並對其調用pauseTimer()

viewController().pauseTimer() // This line causes issue viewController(), creates a new instance 

而不是創建新的對象,無論是你應該是實例傳遞給AppDelegate中並調用pauseTimer()現有的對象或偵聽UIApplicationDidEnterBackgroundNotification通知在你的視圖控制器類和暫停計時器從那裏。

+0

嘗試但它只是「println(」暫停計時器「)」並且不停止計時器 – user528432

+0

@djay:你是怎麼通過這個對象的?請再次閱讀我的答案 –

+0

最新** ** ApplicationWillEnterBackground **的正確代碼是什麼? – user528432

1

接受的答案被@Suresh設置一個觀察者聽,當應用程序確實在你的ViewController的viewDidLoad()方法進入背景

NotificationCenter.default.addObserver(self, selector: #selector(myObserverMethod), name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil) 

添加以下函數以接收通知。

func myObserverMethod(notification : NSNotification) { 

    print("Observer method called") 

    //You may call your action method here, when the application did enter background. 
    //ie., self.pauseTimer() in your case. 

}