5

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?

Aej11
  • 57
  • 6

1 Answers1

5

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"
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690