can I get current location in widgetKit

As far as I can tell in my app I am requesting current location in the app and in the widget the same, but I am not ever seeing my widget make the network call the I would expect if current location was successful.

I have the same info plist permissions for usage and request for access in both the app and the widget ( runs the same shared code ).

My question is does widgetKit work to get core location similar to the the way that today extensions work.

or do I need to cache it from the phone app and hope its been updated ?


Accepted Reply

Core Location should be available to your Widget. I'll assume your network call is custom code. In order to make network calls using your Widget you should use a background session and process the response using onBackgroundURLSessionEvents from your Static or Intent Configuration.

Replies

Core Location should be available to your Widget. I'll assume your network call is custom code. In order to make network calls using your Widget you should use a background session and process the response using onBackgroundURLSessionEvents from your Static or Intent Configuration.
When testing your theory, I first added some debugging by populating the view with some mock data to verify that the location was indeed authorized. From what I can tell the location is either not authorized or never gets set in widgetKit. Thanks for your suggestion to use the background downloader though. Once I get past the getting the coordinates in the widget, I will look into this if its still failing.
You need to make sure you have both these plist values set in your widgets Info.plist file:

Code Block
<key>NSWidgetWantsLocation</key>
<true/>
<key>NSLocationUsageDescription</key>
<string>Put some text here</string>


Then when you open the widget gallery, looks like from beta5 onwards iOS will show a prompt asking you to allow/deny location permissions to the widget.

The next important thing is that inside getTimeline() if you are creating an instance of CLLocationManager you must keep a reference to it past the end of the getTimeline call otherwise no updates will happen on the delegate. In my case I just created a wrapper class that the widget stores as a property then I setup the CLLocationManager instance on the first run of getTimeline and assign it to a field in the wrapper class.

At least this worked for me :)

WidgetKit does not support continuous location updates like today extensions; you should consider caching the location in your phone app and updating it when necessary for your widget.