swiftswiftuiwidgetios14widgetkit

How can I check whether my shared code is running in a WidgetKit widget or full app?


I'm working on a new iOS app with with widgets. Written in SwiftUI.

Most of my code is shared between the Widget target and the App target, but there are some minor style changes I want to make between the two targets.

Is there a way to check whether the code is executing in the widget or in the app?


Solution

  • Here is possible helper function to detect if you run in widget. Tested with Xcode 12 / iOS 14.

    func isInWidget() -> Bool {
        guard let extesion = Bundle.main.infoDictionary?["NSExtension"] as? [String: String] else { return false }
        guard let widget = extesion["NSExtensionPointIdentifier"] else { return false }
        return widget == "com.apple.widgetkit-extension"
    }