iOS14 Widget - 重置倒计时小部件的时间线

时间:2020-12-21 13:28:42

标签: swift widget ios14

我有一个如下定义的倒计时小部件,但是我想知道当日期到达 02/02/2021 时正确的方法是什么?

多久调用一次 getTimeline?每次用户启动应用程序?用户每天是否启动应用程序,或其他什么?

因此我可以按照下面评论中的建议做一些事情吗?

func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
    var entries: [SimpleEntry] = []

    var components = DateComponents()
    
  // Commented lines below contained proposed solution
  //  if ( date < '01/02/2020') {
       components.setValue(2021, for: .year)
  //  }else{
  //      components.setValue(2022, for: .year)
  //  }

    components.setValue(2, for: .month)
    components.setValue(1, for: .day)

    let specialDate = Calendar.current.date(from:components) ?? Date()
 

    let currentDate = Date()

    for dayOffset in 0 ..< 100 {

        let entryNextDate = Calendar.current.date(byAdding: .day, value: dayOffset, to: currentDate)!
        let entryDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: entryNextDate)!

        let calendar = Calendar.current

        // Replace the hour (time) of both dates with 00:00
        let date1 = calendar.startOfDay(for: entryDate)
        let date2 = calendar.startOfDay(for: specialDate)

        let components = calendar.dateComponents([.day], from: date1, to: date2)

        let entry = SimpleEntry(value: "\(components.day ?? 0)", date:entryDate, configuration: configuration)
        entries.append(entry)
    }

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

0 个答案:

没有答案