5

UIApplication has the handy applicationState property that allows you to see if your application is in the background or not. In action (and share) extensions, use of UIApplication is illegal, and even if you do get an instance of it within an extension it always reports applicationState=UIApplicationStateBackground. I also tried observing UIApplicationDidEnterBackgroundNotification, it never fires.

Is there a way to effectively tell if an extension is running within an app that's in the foreground or background?

Tim Johnsen
  • 1,471
  • 14
  • 33

1 Answers1

8

Post iOS 8.2, You can observe the notifications listed here.

NSExtensionHostDidBecomeActiveNotification NSExtensionHostWillResignActiveNotification NSExtensionHostDidEnterBackgroundNotification NSExtensionHostWillEnterForegroundNotification

Be sure to check that you are on a device of the appropriate version before signing up for these notifications, or your extension will crash, as they will be nil.

Ben Pious
  • 4,765
  • 2
  • 22
  • 34
  • Swift 3 format: NSNotification.Name.NSExtensionHostDidEnterBackground – xaphod Mar 13 '17 at 15:40
  • I'm seeing that the didBecomeActive and willEnterForeground notifications don't fire the first time my sharing extension is used with the host app. They only occur the second, etc. time it is used. – Chris Prince Mar 21 '21 at 16:10