Eric
Eric

Reputation: 769

How to detect when a user terminates an app - Swift

Not sure why this is so challenging for me, but how can I detect when the user terminates the app? Because from what I'm seeing, Apple provides a lot of functions that might or might not be called when an app closes.

func applicationWillTerminate(_ application: UIApplication): Called when (most) apps are terminated, but not for apps that support background execution.

func sceneDidEnterBackground(_ scene: UIScene): Called when the scene enters the background, but can't differentiate between the app entering the background versus terminating completely.

func sceneDidDisconnect(_ scene: UIScene): I confirmed this is called if the user directly terminates the app, but if the app is put in the background and then terminated, it isn't called..

// EDIT: So I realized the above method (sceneDidDisconnect) is indeed the function I was looking for. I previously thought it wasn't being called in the latter case described above, but in actuality, it was. See the (soon to be) accepted answer as well.

Is there a function that's called every time a user terminates an app???

Upvotes: 7

Views: 3982

Answers (2)

Uch
Uch

Reputation: 244

I'm using React Native 73 so SceneDelegate isn't available for me. I have to use AppDelegate.mm. The way I'm able to detect when the user terminates the app (somewhat reliably) is by using applicationWillTerminate. For whatever reason, in XCode, it only gets logged once per app initialization, but it actually does fire every time the user swipes away the app once it's built.

@implementation AppDelegate
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [FIRApp configure]; // If you're using react-native firebase
  logger = os_log_create("com.uchenkadi.swoltime", "AppDelegate");

  self.moduleName = @"main";
  // You can add your custom initial props in the dictionary below.
  // They will be passed down to the ViewController used by React Native.
  self.initialProps = @{};
  
  bool didFinish = [super application:application didFinishLaunchingWithOptions:launchOptions];
  
   [RNSplashScreen show];  // this needs to be called after [super application:application didFinishLaunchingWithOptions:launchOptions];
   
   return didFinish;
}

- (void)applicationWillTerminate:(UIApplication *)application {
  // do stuff in here!
}
@end

Upvotes: 0

Eric
Eric

Reputation: 769

func sceneDidDisconnect(_ scene: UIScene) ended up being the function I was looking for. It's called whenever the user manually "terminates" the app...

...although as @dfd commented

"In iOS, typically it's the OS that terminates an app for a variety of reasons (not necessarily the user)."

Upvotes: 4

Related Questions