簡體   English   中英

如何使計時器在后台Xcode IOS中運行

[英]How to Make Timer Run in Background Xcode IOS

我的應用程序有問題。 我有一個在應用程序中運行的倒數計時器。 最初,在我調整應用程序委托方法applicationDidEnterBackground ,如果我離開應用applicationDidEnterBackground ,計時器仍將運行(不關閉應用程序,僅在主屏幕上)。

我在applicationDidEnterBackground放置了一個通知觸發器。 這可能導致計時器停止運行。

我需要在計時器結束之前向用戶發送通知以返回到應用程序。 (因此通知在applicationDidEnterBackground )我想給用戶一定的時間,使其在計時器停止之前返回到應用程序。

現在....通知已發送,但計時器立即結束。

func applicationDidEnterBackground(_ application: UIApplication) {
    let content = UNMutableNotificationContent()
    //adding title, subtitle, body and badge
    content.title = "Hey if you will not come back"
    content.subtitle = "your timer will be killed"
    content.body = ""
    content.badge = 1
    //getting the notification trigger
    //it will be called after 5 seconds

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)

    //getting the notification request
    let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)


    //adding the notification to notification center
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

ViewController.swift

 @objc func countdown (){

    if valueToInt != 0 {
        valueToInt -= 1
        sliderLabel.text = String(valueToInt)
    } else {
        endTimer()
    }

    sliderLabel.text = timeFormatted(valueToInt)
}


func startTimer() {

    countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector (ViewController.countdown), userInfo: nil, repeats: true)

    countdown()

    stopOutlet.isHidden = false
    startOutlet.isHidden = true
    titlleLabel.isHidden = true
    sliderView.isHidden = true

 }

除非明確要求,否則您不能在后台連續運行任何代碼。 要執行任何后台任務,您必須激活后台模式。 目標->功能->背景模式對於所需的特定解決方案,您可以在不打開背景模式的情況下要求系統在背景中多留點時間。 蘋果將​​為您提供2分鍾59秒的最長時間,這是我測試過的時間,但文檔僅說了3分鍾。

// Declare a background task by default I set it to TaskInvalid
var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid

在進入后台模式之前,啟動並開始后台任務

backgroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: { [weak self] in
        self?.endBackgroundTask()
    })

// endBackgroundTask is a helper function which you will call once you're done with your task
private func endBackgroundTask() {
    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
}

您甚至可以在使計時器無效之前調用endBackgroundTask函數

 @objc func countdown (){

if valueToInt != 0 {
    valueToInt -= 1
    sliderLabel.text = String(valueToInt)
} else {
    // call endBackgroundTask if you didn't call system will terminate it
    self.endBackgroundTask()
    endTimer()
}

   sliderLabel.text = timeFormatted(valueToInt)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM