Apple Watch complication network requests

835 Views Asked by At

I'm creating a weather application that pulls its information from an online API.

I am able to get the information successfully in the GlanceController and in the InterfaceController. However, I'm a little unsure as to how I should do this for the complication. Can I perform a network request within the ComplicationController class?

If so, How would I go about doing this?

1

There are 1 best solutions below

0
On BEST ANSWER

You'll run into issues related to asynchronously fetching data from within the complication data source, mostly due to the data being received after the timeline update is complete.

Apple recommends that you fetch the data from a different part of your app, and have it available in advance of any complication update:

The job of your data source class is to provide ClockKit with any requested data as quickly as possible. The implementations of your data source methods should be minimal. Do not use your data source methods to fetch data from the network, compute values, or do anything that might delay the delivery of that data. If you need to fetch or compute the data for your complication, do it in your iOS app or in other parts of your WatchKit extension, and cache the data in a place where your complication data source can access it. The only thing your data source methods should do is take the cached data and put it into the format that ClockKit requires.

Other ways to approach it:

  • The best way to update your complication (from your phone once you have received updated weather data) is to use transferCurrentComplicationUserInfo.

  • Alternately, you could have your watch app or glance cache its most recent weather details to be on hand for the next scheduled update.

If you absolutely must handle it from the complication:

You could have the scheduled timeline update get the extension to start an NSURLSession background task to asynchronously download the information from your weather service. The first (scheduled) update will then end, with no new data. Once the new weather data is received, you could then perform a second (manual) update to reload the complication timeline using the just-received data.

I don't have any personal experience with that approach, mostly because of the unnecessary need for back-to-back timeline updates.