设置Widget的TimelineProvider刷新间隔

sub*_*ner 5 swift widgetkit swiftui

现在我的 Widget 每秒发出大约 1 个请求。我想将其更改为 1 小时内 1 个请求。

我在网上遇到了一些let timeline = ...类似的错误Value of optional type 'Date?' must be unwrapped to a value of type 'Date'以及更多错误。

任何可能出错的建议:

struct Provider: IntentTimelineProvider {
    let networkManager = NetworkManager()
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date(), configuration: ConfigurationIntent(), clubname: networkManager.clubName)
    }
    
    func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), configuration: configuration, clubname: networkManager.clubName)
        completion(entry)
    }
    
    func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        var entries: [SimpleEntry] = []
        
        // Generate a timeline consisting of five entries an hour apart, starting from the current date.
        let currentDate = Date()
        for hourOffset in 0 ..< 5 {
            let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
            let entry = SimpleEntry(date: entryDate, configuration: configuration, clubname: networkManager.clubName)
            entries.append(entry)
        }
        
        //wie oft geupdatet werden soll
        
        let nextUpdate = Calendar.current.date(byAdding: .hour, value: 1, to: Date())
        
        let timeline = Timeline(entries: entries, policy: .after(nextUpdate))
        completion(timeline)
    }
}
Run Code Online (Sandbox Code Playgroud)

paw*_*222 6

您不应该依赖TimelineReloadPolicy- 它指定刷新时间轴的最早日期,不能保证它在该特定时间重新加载。

根据我的观察,Widget 更有可能使用atEnd策略重新加载时间线。

指定 WidgetKit 在时间线中的最后一个日期过后请求新时间线的策略。

这是一个可能的解决方案:

func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
    print("getTimeline")
    let entries = [
        SimpleEntry(date: Date()),
        SimpleEntry(date: Calendar.current.date(byAdding: .minute, value: 1, to: Date())!),
    ]

    let timeline = Timeline( entries: entries, policy: .atEnd)
    completion(timeline)
}
Run Code Online (Sandbox Code Playgroud)

请注意,最后一个条目可能会被使用,也可能不会被使用。如果在第二个条目的日期之后立即刷新时间线,则不会显示第二个条目。但是,有时时间线可能会延迟重新加载 - 然后第二个条目将可见(直到刷新时间线)。