Xcode SwiftUI从后台计时器更新文本标签
我想建立一个计时器巫婆一直在后台运行。 设置倒计时后,我保存计划时间并将其与当前时间进行比较 如何使用计算出的差异更新文本标签?我想显示剩余时间,并在倒计时达到0时触发另一个事件 以下是我目前的代码:Xcode SwiftUI从后台计时器更新文本标签,xcode,background,swiftui,countdown,Xcode,Background,Swiftui,Countdown,我想建立一个计时器巫婆一直在后台运行。 设置倒计时后,我保存计划时间并将其与当前时间进行比较 如何使用计算出的差异更新文本标签?我想显示剩余时间,并在倒计时达到0时触发另一个事件 以下是我目前的代码: import SwiftUI import UserNotifications struct ContentView: View { @State var start = false // Btn-Trigger @State var notifyTime = Da
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
}
非常感谢您的建议。将您的
正文更改为
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
}
})
}