How to query WidgetKit if my widgets are being used?
Asked Answered
C

3

6

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.
Carliecarlile answered 27/8, 2020 at 5:8 Comment(2)
were you ale to solve it? doesn't widgetCenter.getCurrentConfigurations gets the used one by the app? , this is what I'm currently seeing.Scheel
It was what I've seen when I tried but it has been a while since then. I am not sure if the behaviour of the method changed or apple suggested another way to achieve what we want. I don't know the current situation but we were not able to find a solution.Carliecarlile
T
2

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.

Theocrasy answered 9/11, 2021 at 12:16 Comment(1)
Thanks! This has allowed me to get rid of a complicated code that was writing a flag from a widgetkit process :).Divisionism
E
0

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.

Erepsin answered 6/11, 2020 at 16:43 Comment(0)
P
0

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

Pueblo answered 12/7, 2024 at 12:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.