Mark Carols Mark Carols - 6 days ago 5
Swift Question

Send request to web service when app gets killed? (Swift 3)

It's very important for my app to be notified every time the user kills my app (not moving it to the background, but actually quitting it altogether by double-tapping the Home button and swiping my app screenshot up). I know

applicationWillTerminate()
barely ever gets called, so I was wondering what the safest way is to be notified when a user will kill the app. It seems very unlikely that Apple hasn't provided ANY form of solution for this, as a lot of iOS users make it a custom to kill apps when they're done using it, so it would be really really REALLY weird if it would be impossible to catch this event. The only thing I need to do is fire off a
URLRequest
to send some updating instructions to my web service.

Answer

I get more consistency when I add an observer to handle UIApplicationWillTerminateNotification. It gets called when the user double-taps the Home button and swipe the app to kill it.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool 
{
  NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(AppDelegate.onAppWillTerminate(_:)), name:UIApplicationWillTerminateNotification, object:nil)
  return true
}


func onAppWillTerminate(notification:NSNotification)
{
  print("onAppWillTerminate")
}
Comments