How to query WidgetKit if my widgets are being used?

Viewed 723

I would like to check if the user added my widgets to the Home Screen, is there an API for this? I could not find one. WidgetCenter.getCurrentConfigurations returns all available widgets served by the app, not the used ones.

The reasons I look for such an API are:

  1. I would like to report usages of the widgets.
  2. I would like to decide if I should trigger timeline reloads via WidgetCenter when state changes happen in the app.
2 Answers

Unfortunately, I don't think such an API exists (yet).

For 1. I would write something that identifies the widget in a shared user defaults container. Hooks for that would be getSnapshot(for:,in:,completion:) or getTimeline(for:,in:,completion:) with context.isPreview == false. Now the difficult part is that you don't get any id for the widget so you cannot distinguish two widgets with the same configuration (afaik).

For 2. I think this is (and will be) opaque, so you just tell the WidgetCenter to reload specific or all configurations and when no widget is currently placed on the home screen nothing happens.

Method WidgetCenter.shared.getCurrentConfigurations does return the number of user configured widgets:

WidgetCenter.shared.getCurrentConfigurations { widgets 
    if let widgets = widgets, widgets.count > 0 {
        // User did configure at least one widgets
    }
}

This is also according the documentation:

Retrieves information about user-configured widgets.

Related