【问题标题】:Can't get Apple Watch complication to update in WatchOS 3无法在 WatchOS 3 中更新 Apple Watch 复杂功能
【发布时间】:2017-11-22 05:03:10
【问题描述】:

我无法在 WatchOS 3 中更新/刷新 Apple Watch 复杂功能。我在 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()
    }
}

【问题讨论】:

    标签: ios swift watchkit watchos-3 clockkit


    【解决方案1】:

    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)
    

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

    更多关于并发症更新in documentation。更多关于后台任务in WWDC16 session

    【讨论】:

    • 谢谢!调用scheduleNextRefresh() 方法的最佳位置在哪里?我已经在 awake 方法中的手表应用的界面控制器中完成了。
    • 一般来说,您希望在新数据到达时更新复杂性,以便从该位置调用调度后台任务。但是请注意scheduleBackgroundRefresh 的完成处理程序在后台刷新计划 时被调用,而不是执行,developer.apple.com/documentation/watchkit/wkextension/… 的文档有错误。见这里:stackoverflow.com/questions/41238434/…
    • 这对我不起作用 - 没有任何变化,getCurrentTimelineEntry(for:withHandler:) 不会被调用
    猜你喜欢
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 2016-03-17
    • 1970-01-01
    相关资源
    最近更新 更多