2

I am looking for an swift method that acts like onDestroy() in android. I want it not to be called when the home button is pressed, it should only be called when the application is quit entirely. I tried using the deinit method but it was never called.

Abizern
  • 146,289
  • 39
  • 203
  • 257
cvrattos
  • 51
  • 1
  • 4

4 Answers4

0

A suitable equivalent in an iOS environment is applicationWillTerminate(_:) inside AppDelegate.

Keep in mind that asynchronous operations cannot be executed here properly.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
0

If the user pressed the home button and went to the phone screen menu, then the app is in the background state. This function will get called:

optional func applicationDidEnterBackground(_ application: UIApplication)

If the user terminated the app by double pressing the home button and swiping the app up, or by having the app in the bacground for more than 3 minutes then this method will get called:

optional func applicationWillTerminate(_ application: UIApplication)

Both functions are already there in your AppDelegate class.

Hope this helps!

Mohamad Bachir Sidani
  • 2,077
  • 1
  • 11
  • 17
0

iOS equivalent doesn't exist. You can use

optional func applicationWillResignActive(_ application: UIApplication)

it's called when the app is leaving the foreground state.

or

optional func applicationWillTerminate(_ application: UIApplication)

this one one is called only when the app is running, i.e. in most cases it will not be called when the app is in background, unless it has special permissions.

deinit will not be called when the app is terminated, because its purpose is to execute when an object is destroyed to free up memory. When the app is terminated, the whole process is destroyed among with its memory stack, so freeing memory is pointless.

Max Pevsner
  • 4,098
  • 2
  • 18
  • 32
0

There used to be a viewDidUnload method in iOS but it's been deprecated since iOS 6. Another option, since a lot of people are mentioning applicationWillTerminate, you could maybe register for the UIApplicationWillTerminate notification, associate it to a function and do whatever you want in that function such as cleanup and such.

Alan
  • 1,132
  • 7
  • 15