SwiftUI 从后台计时器更新 Textlabel

SwiftUI update Textlabel from Background Timer

我想构建一个计时器 让 运行 在后台运行。 设置好倒计时后,我把预定的时间保存下来,和现在的时间对比一下。

如何使用计算出的差异更新文本标签?我想显示剩余时间并在倒计时到 0 时触发另一个事件。

到目前为止,这是我的代码:

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
}

非常感谢您的建议。

将您的 body 更改为。

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
        }
    })
}