无法在WatchOS 3中更新Apple Watch复杂功能

时间:2017-06-19 20:49:11

标签: ios swift watchkit watch-os-3 clockkit

我无法在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))
}

我还尝试从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()
    }
}

1 个答案:

答案 0 :(得分:4)

WKRefreshBackgroundTask不会自行更新任何内容,只是允许您的应用进入活动状态并运行代码(位于print("Task received")行附近),这将更新您的并发症。请记住,WKRefreshBackgroundTask的数量是有限的。

可以通过以下方式更新并发症:

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)

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

有关并发症更新in documentation的更多信息。有关后台任务的更多信息in WWDC16 session