如何解决SwiftUI从后台计时器更新Textlabel
我想建立一个计时器,让女巫一直在后台运行。 设置倒计时后,我将保存计划时间并将其与当前时间进行比较。
如何使用计算出的差异更新文本标签?我想显示剩余时间并在倒数到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
}
})
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。