在一天的特定时间使用合并运行代码

问题描述 投票:0回答:1

我的目标是在一天的特定时间使用合并运行代码。在下面的代码中,当计时器触发时,我使用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
        }
    }
}
ios swift swiftui combine
1个回答
0
投票

由于即使在应用程序不是前台的情况下也想做某事,所以需要使用the UserNotifications framework

读取“Scheduling a Notification Locally from Your App”

基本摘要是:

  • 创建UNMutableNotificationContent
  • 创建UNCalendarNotificationTrigger
  • 使用内容和触发器创建UNNotificationRequest
  • 将请求添加到UNUserNotificationCenter
© www.soinside.com 2019 - 2024. All rights reserved.