Widgets have been one of the top features of iOS 14 during WWDC 2020, where the biggest change ever of iOS home screen has been unveiled. On the user point of view, they represent a new type of interaction, a new entry point for apps; on a technology point of view, they are a manifesto of the way chosen by Apple, where SwiftUI (the only way to build widget’s views) and an optimized universality (widgets are available on iOS, iPadOS and macOS) are key elements.

After experimenting with the WidgetKit framework on iOS 14 and Xcode 12 betas, I want to share 10 interesting tips that could be useful for many use cases when coding widgets for your apps. Disclaimer: I assume you already know how to create a simple widget and basic related APIs. Let’s start! 👨🏼‍💻

1. UserDefaults Suite

Very likely, you’ll need to use UserDefaults from your widgets, in order to read user preferences or some other small amount of data. To do so, the standard container isn’t the way, because its content isn’t shared between different targets; instead, as for any other app extension, you have to rely (from the app and from widgets) to the shared “suite”, named with the App Group ID, using the dedicated api:

let userDefaults = UserDefaults(suiteName: “your-app-group-id”)

The App Group is a capability available in the “Signin & Capabilities” tab of your targets: remember to add the App Group capability both in the app’s target and in the widget’s target, otherwise it won’t work.

2. Location permission

As a general rule, widgets inherit every permission status from the parent app and it’s not allowed to prompt requests from the widget itself. Location permission represents an exception: starting from beta 5, when a widget using location is added to the home screen, the user will be _automatically_requested to grant permission through an alert; the choice can be changed anytime from the Settings, as a new “While Using the App or Widgets” option is available.

Image for post

In addition, remember to put the NSWidgetWantsLocation (boolean) and NSLocationUsageDescription keys in the widget extension Info.plist to get location services work properly.

Image for post

Image for post

3. Maps with MKMapSnapshotter

Talking about location, another question could come up: what is the best way to present a map view inside a widget? The recommended option is to use a MKMapSnapshotter in place of a MKMapView; in fact, the standard map view doesn’t work at all. The snapshot captures the map’s contents in a simple image. To get the desired MKMapSnapshotter.Snapshot:

The closure is perfect to be used in the getTimeline(in:completion:)function of TimelineProvider protocol: once the image is loaded, you can create your entries and define the timeline. The snapshot is highly customizable and you find the full documentation here.

#swift #ios #swiftui #xcode #widget

10 Tips on Developing iOS 14 Widgets
17.50 GEEK