Search code examples
xcodebackgroundswiftuicountdown

SwiftUI update Textlabel from Background Timer


I would like to build a timer witch keeps running in the background. When the countdown is set, I save the scheduled time and compare it with the current time.

How do I update the text label with the calculated difference? I want to show the remaining time and trigger another event when the countdown reaches 0.

Here is my code so far:

import SwiftUI
import UserNotifications

struct ContentView: View {
    @State var start = false        // Btn-Trigger
    @State var notifyTime = Date()  // EndTime
    @State var timeLeft = 10
    
    var body: some View {
        VStack {
            Text("\(timeLeft)")
            
            Button(action: {
                self.start.toggle()
                self.notifyTime = Date().addingTimeInterval(TimeInterval(10)) // add  countdown time in sec
                self.timeLeft = timeDifference(endTime: self.notifyTime)
                self.sendNotification()
            }) { Text("Start Countdown (10s)")}
            
        }.onAppear(perform: {
            UNUserNotificationCenter.current().requestAuthorization(options: [.badge,.sound,.alert]) { (_, _) in
            }
        })
    }
    
    func sendNotification() {
            let content = UNMutableNotificationContent()
            content.title = "Title"
            content.body = "Body"
            content.sound = UNNotificationSound.default

            let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second,], from: notifyTime)
            let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
            
            let request = UNNotificationRequest(identifier: "MSG", content: content, trigger: trigger)
            print("INSIDE NOTIFICATION")
            
            UNUserNotificationCenter.current().add(request, withCompletionHandler: {(error) in
                if error != nil {
                    print("SOMETHING WENT WRONG")
                }
            })
        }
}

func timeDifference(endTime: Date) -> Int {
    let diffComponents = Calendar.current.dateComponents([.minute, .second], from: Date(), to: endTime)
    return diffComponents.second ?? 2507
}

Thanks you very much for your suggestions.


Solution

  • Change your body to.

    var body: some View {
        VStack {
            Text("\(timeLeft)")
            
            Button(action: {
                self.start.toggle()
                self.notifyTime = Date().addingTimeInterval(TimeInterval(10)) // add  countdown time in sec
                self.timeLeft = timeDifference(endTime: self.notifyTime)
                self.sendNotification()
                //Timer code - Start your timer
                Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
                    timeLeft -= 1
                    
                    if timeLeft == 0 {
                        timer.invalidate()
                        //Add your new trigger event
                    }
                }
            }) { Text("Start Countdown (10s)")}
            
        }.onAppear(perform: {
            UNUserNotificationCenter.current().requestAuthorization(options: [.badge,.sound,.alert]) { (_, _) in
            }
        })
    }