How to change view on midnight in WidgetKit, SwiftUI?

白昼怎懂夜的黑 提交于 2021-02-15 04:58:30

问题


I have a code:

struct ContentView: View {
    let entry: LessonWidgetEntry
    private static let url: URL = URL(string: "widgetUrl")!
    var body: some View {
        VStack {
            switch entry.state {
            case .none:
                ProgramNotStartedView()
            case .currentLesson(let lesson):
                LessonView(lesson: lesson, imageName: entry.program?.imageName)
            case .lessonCompleted(let lesson):
                LessonCompletedView(lesson: lesson)
            case .programCompleted:
                ProgramCompletedView()
            }
        }.widgetURL(ContentView.url)
    }
}

At midnight LessonCompletedView should change to LessonView, but I am not sure how to do that. Any ideas on how to change views on midnight from the widget?


回答1:


  1. Assuming you have an Entry (in your app you have entry.state... but for this example I used a simplified version):
struct SimpleEntry: TimelineEntry {
    let date: Date
    let lesson: Lesson
}
  1. Setup your TimelineProvider to refresh timeline after the next midnight:
struct SimpleProvider: TimelineProvider {
    ...

    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
        let currentDate = Date()
        let midnight = Calendar.current.startOfDay(for: currentDate)
        let nextMidnight = Calendar.current.date(byAdding: .day, value: 1, to: midnight)!

        let entries = [
            SimpleEntry(date: entryDate, lesson: Lesson()) // pass the lesson here
        ]

        let timeline = Timeline(entries: entries, policy: .after(nextMidnight))
        completion(timeline)
    }
}

In the TimelineProvider you may pass any lesson you want (depending on the day or the previous lesson - it's up to you). You may also pass a variable to an Entry indicating whether the lesson is completed.

By setting the .after(nextMidnight) policy you indicate when do you want your Timeline (and therefore you Widget View) to be reloaded.



来源:https://stackoverflow.com/questions/64209612/how-to-change-view-on-midnight-in-widgetkit-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!