Im trying to build a timer which continuing counting down when the app is in the background or even the screen is locked. After the timer reached 0 a notification should been send.
So far it works on the simulator but not on the real device (iPhone X, running iOS 13.5.1). The task simply pauses when entering background.
How do I keep the countdown running on the real device?
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)
}
}