无法在WatchOS 3中更新Apple Watch并发症

use*_*227 2 ios swift watchkit clockkit watchos-3

我无法在WatchOS 3中更新或刷新Apple Watch Complication。我在ComplicationController.swift文件中使用以下代码。

func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) {
    handler([.forward])
}

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

func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
    handler(Date(timeIntervalSinceNow: 60 * 30))
}
Run Code Online (Sandbox Code Playgroud)

我也曾尝试从中的handle后台任务方法安排更新,ExtensionDelegate.swift但它似乎也不起作用。

func scheduleNextRefresh() {
    let fireDate = Date(timeIntervalSinceNow: 30 * 60)
    let userInfo = ["lastActiveDate" : Date(),
                    "reason" : "updateWeekNumber"] as Dictionary

    WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: fireDate, userInfo: userInfo as NSSecureCoding) { (error) in
        if error == nil {
            print("Succesfully updated week number")
        }
    }
}

func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
    for task: WKRefreshBackgroundTask in backgroundTasks {
        if WKExtension.shared().applicationState == .background {
            if task is WKApplicationRefreshBackgroundTask {
                print("Task received")
                scheduleNextRefresh()
            }
        }
        task.setTaskCompleted()
    }
}
Run Code Online (Sandbox Code Playgroud)

abj*_*ato 5

WKRefreshBackgroundTask本身不会进行任何更新,它仅允许您的应用进入活动状态并运行代码(位于代码print("Task received")行附近)以更新您的复杂性。请记住,WKRefreshBackgroundTasks的数量是有限的。

并发症可以这样更新:

let server = CLKComplicationServer.sharedInstance()

// if you want to add new entries to the end of timeline
server.activeComplications?.forEach(server.extendTimeline)

// if you want to reload all the timeline, which according to snippets looks like your case
server.activeComplications?.forEach(server.reloadTimeline)
Run Code Online (Sandbox Code Playgroud)

这将导致系统调用的getCurrentTimelineEntry(for:withHandler:)方法CLKComplicationDataSource,您可以在其中准备并返回更新的条目。

有关并发症的更多信息,请参见文档。有关WWDC16会话中的后台任务的更多信息。