我的目标是在一天的特定时间使用合并运行代码。在下面的代码中,当计时器触发时,我使用Combine来更新SwiftUI文本视图。我希望文本视图在一天的特定时间更新,而不是在计时器触发时更新。我相信NotificationCenter可以用于此目的,但是由于缺乏文档,我不确定如何使这项工作有效。
您能否解决此问题,并使用通知中心在一天的特定时间(例如,下午6点)更新textview?
import SwiftUI
struct ContentView: View {
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
@State private var counter = 0
var body: some View {
Text("The time is now \(counter)")
.onReceive(timer) { time in
if self.counter == 30 {
self.timer.upstream.connect().cancel()
}
self.counter += 1
}
}
}
由于即使在应用程序不是前台的情况下也想做某事,所以需要使用the UserNotifications framework。
读取“Scheduling a Notification Locally from Your App”。
基本摘要是:
UNMutableNotificationContent
。UNCalendarNotificationTrigger
。UNNotificationRequest
。UNUserNotificationCenter
。