Search code examples
watchkitapple-watchapple-watch-complication

How to update Apple Watch complications automatically?


Currently, my code doesn't work. I still have to manually refresh it. I want the complication to automatically update every 12 hours.

func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {

    let date = Calendar.current.startOfDay(for: Date())
    print("timeline start date :\(date)")
    handler(date)
}

func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
    var  date = Calendar.current.startOfDay(for: Date())
    date = Calendar.current.date(byAdding: .day, value: 2, to: date)!
    print("timeline end date:\(date)")
    handler(date)
}

func getNextRequestedUpdateDate(handler: @escaping (Date?) -> Void){
    handler(Date(timeIntervalSinceNow: 60*60*12))


}

Solution

  • It seems the data source methods are not implemented. It's needed to be implemented for the refresh.

    At the start of a scheduled update, ClockKit calls either the requestedUpdateDidBegin or requestedUpdateBudgetExhausted method, depending on the state of your complication’s time budget. You must implement one or both of those methods if you want to add data to your timeline. Your implementation of those methods should extend or reload the timeline of your complication as needed. When you do that, ClockKit requests the new timeline entries from your data source. If you do not extend or reload your timeline, ClockKit does not ask for any new timeline entries.

    func requestedUpdateDidBegin() {
        let server=CLKComplicationServer.sharedInstance()
        for complication in server.activeComplications {
            server.reloadTimelineForComplication(complication)
        }
    }
    

    For more information check this.