【发布时间】:2020-07-10 22:32:49
【问题描述】:
我正在尝试构建一个计时器,当应用程序在后台甚至屏幕被锁定时,它会继续倒计时。计时器达到 0 后,应发送通知。
到目前为止,它可以在模拟器上运行,但不能在真实设备上运行(iPhone X,运行 iOS 13.5.1)。进入后台时任务只是暂停。
如何在真实设备上保持倒计时?
import SwiftUI
import UserNotifications
struct ContentView: View {
@State var start = false
@State var count = 10 // 10 sec timer
@State var time = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View{
VStack{
Text("\(self.count)")
Button(action: {
self.start.toggle()
}) {
Text("Start")
}
}
.onAppear(perform: {
UNUserNotificationCenter.current().requestAuthorization(options: [.badge,.sound,.alert]) { (_, _) in
}
})
.onReceive(self.time) { (_) in
if self.start{
if self.count != 0{
self.count -= 1
}
else{
self.sendNotification()
}
}
}
}
func sendNotification(){
let content = UNMutableNotificationContent()
content.title = "Timer"
content.body = "Time is up!"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let req = UNNotificationRequest(identifier: "MSG", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(req, withCompletionHandler: nil)
}
}
【问题讨论】:
-
Timer在您的应用暂停时不会运行。您可以使用Timer来更新您的用户界面,但您不能使用简单的计数器来跟踪时间。您需要计算计时器的结束日期并使用它来确定时间到了。如果您的应用有可能在发生这种情况时被暂停,您可以考虑在计时器到期时安排通知