【问题标题】:Setting the TimelineProvider refresh interval for Widget设置 Widget 的 TimelineProvider 刷新间隔
【发布时间】:2021-01-08 14:46:12
【问题描述】:

现在我的小部件每秒大约发出 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)
    }
}

【问题讨论】:

    标签: swift swiftui widgetkit


    【解决方案1】:

    您不应依赖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)
    }
    

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

    【讨论】:

    • 谢谢。我发现了我必须删除一些每次请求时都会执行的代码的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多