Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
918 views
in Technique[技术] by (71.8m points)

ios - How to change view on midnight in WidgetKit, SwiftUI?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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: currentDate, 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...