mehmet6parmak
mehmet6parmak

Reputation: 4857

How to query WidgetKit if my widgets are being used?

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.

Upvotes: 6

Views: 1832

Answers (3)

Emirhan Karahan
Emirhan Karahan

Reputation: 140

I recommend checking this GitHub repository. It uses WidgetKit's getCurrentConfigurations method and stores the configuration in UserDefaults. By comparing the previous configuration, it determines if a widget has been removed or added.

JagerYoo WidgetDestroyer Github

Upvotes: 0

Ely
Ely

Reputation: 9131

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.

Upvotes: 2

fruitcoder
fruitcoder

Reputation: 1218

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.

Upvotes: 0

Related Questions