watchOS - 显示并发症的实时出发数据

watchOS - Show realtime departure data on complication

我有一个 public 运输应用程序,其中包含火车的实时出发数据。 我想添加一个显示下一班火车出发时间的复杂功能。

是否可以显示(或刷新)复杂功能的实时数据?例如,显示“3 分钟到 X 站”。根据来自 public 传输 API.

的信息,数据每分钟都可能发生变化

我应该如何在 watchOS 2 或 watchOS 3 上完成此操作?

我知道 ETA 应用程序会在复杂功能中显示行程时间,但我不确定他们是如何实现的。

是否可以实时更新?

  • 复杂功能并非旨在显示实时数据。频繁更新会影响能源效率并影响电池(在手表和 phone 上)。

    To minimize power usage, ClockKit asks you to provide as much data as you have available and then caches the data and renders it when needed.

  • 虽然没有固定的时间线可以重新加载的次数,但复杂数据源受每日执行时间预算的限制。

    If your app’s data changes frequently, it might be difficult to provide enough data to display in a complication. Worse, if you refresh your complication data too frequently, you may exceed your execution time budget and your complication might not be updated until the following day.

  • 一旦每日预算用尽,调用 reloadTimeline (and extendTimeline) 什么也不做。

    If your complication has already exceeded its allotted daily budget for execution time, calls to this method do nothing. Call this method sparingly.

复杂功能如何显示相对时间?

  • 您可以使用 CLKRelativeDateTextProvider 创建格式化的相对时间,该时间可以按分钟更改。

    A CLKRelativeDateTextProvider object creates a formatted string that conveys the difference in time between the current date and a date that you specify. You use a relative date text provider to implement timers or other relative time values in an efficient way. Instead of using multiple timeline entries to replicate a countdown timer, create a single timeline entry with a relative date text provider. When the user views the clock face, ClockKit automatically updates the relative time value in your complication, providing up-to-date time information.

复杂功能怎么会频繁更新?

  • 您可以使用复杂功能推送更新(来自远程服务器,或本地来自 iOS 10 中的 phone)。

    每天有 50 个并发症推送更新的限制。

  • 您可以在 phone 上获取数据并使用 transferCurrentComplicationUserInfo

    在 watchOS 2 中,这仅受每日预算的限制。在 watchOS 3 中,现在限制为每天 50 次传输。

    有关详细信息,请参阅

  • 在 watchOS 2 中,您可以使用 getNextRequestedUpdateDate 安排下一次更新您的复杂功能。

    这种情况最多只能每十分钟发生一次。

    请注意,watchOS 3 应用程序应升级为使用后台刷新应用程序任务。主要好处是后台任务能够做的不仅仅是更新您的并发症。他们还可以处理获取数据、在数据到达后更新模型以及更新停靠快照。

  • 最后,您可以安排手动更新。在 watchOS 3 中,推荐的方法是通过后台刷新应用任务。

    任务预算允许每小时 4 个任务。有关详细信息,请参阅 scheduleBackgroundRefresh

    请注意,后台刷新应用程序任务不得使用超过 10% CPU。

推荐的 WWDC 2016 会话

如会谈中所述,您应该将更新安排在需要更新的时间左右。

对于您的用例,示例仅在 public 中转 运行 时,并且仅在定期安排的出发时间会受到延误影响时。

Apple 示例代码

Apple 提供 WatchBackgroundRefresh 示例代码演示如何使用 WKRefreshBackgroundTask 在后台更新 WatchKit 应用程序。

要在后台任务中更新任何活动的复杂功能,您只需添加代码以重新加载(或延长)时间线:

let complicationServer = CLKComplicationServer.sharedInstance()

for complication in activeComplications {
    complicationServer.reloadTimelineForComplication(complication)
}