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

1.7k views Asked by At

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?

2

There are 2 answers

0
Asperi On BEST ANSWER

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"
}
0
budiDino On

One approach would be to go to the Build Settings of your widget's target, and under Swift Compiler - Custom Flags, Active Compilation Conditions add something like WIDGET to Alpha, Debug, and Release.

Then in your code use:

var title = "app title"
#if WIDGET
    // Do stuff only when compiling the widget
    title = "widget title"
#endif