如何在 iOS 應用中後臺執行計時器


如果您希望在 iOS 應用程式中後臺執行計時器,Apple 提供了 beginBackgroundTaskWithExpirationHandler 方法,您可以閱讀更多相關資訊  https://developer.apple.com/documentation/uikit/uiapplication/1623031-beginbackgroundtaskwithexpiration

我們將使用相同的 method 來編寫我們在後臺執行計時器的程式碼。

讓我們開始吧。

步驟 1 - 開啟 Xcode → 單檢視應用程式 → 我們將其命名為 BackgroundTimer。

步驟 2 - 開啟 AppDelegate.swift,並在 applicationDidEnterBackground 方法下編寫以下程式碼。

backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
   UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})
= Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.doSomething), userInfo: nil, repeats: true)

步驟 3 - 編寫新的函式 doSomething()

@objc func doSomething() {
   print("I'm running")
}

最終您的程式碼應如下所示

func applicationDidEnterBackground(_ application: UIApplication) {
   backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
      UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
   })
   _ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.doSomething), userInfo: nil, repeats: true)
}
@objc func doSomething() {
   print("I'm running")
}

執行應用程式

當應用程式轉到後臺時,我們在這裡列印“我正在執行”。當應用程式進入後臺時,“我正在執行”將開始在控制檯中列印。點選主頁按鈕並進行測試。但是,根據 Apple 文件的規定並經過測試,當您的應用程式處於後臺時,您可以最多執行計時器 3 分鐘。

執行此應用程式時,將應用程式置於後臺並等待 3 分鐘,您會看到 3 分鐘後“我正在執行”不會列印。現在將應用程式置於前臺,您會注意到“我正在執行”開始列印。

更新於:2019年7月30日

瀏覽量 1000+

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告