Reputation: 8707
it it possible to detect before the iPhone shuts down to call actions like saving data to persistent store etc. for Swift
I tried the appWillEnterBackground
and appWillTerminate
function, but it didn´t work when i shut down the phone in app
Upvotes: 2
Views: 1241
Reputation: 5237
There is no direct API in Swift to detect when an iPhone will shut down, as Apple doesn't expose this information to third-party apps for security and privacy reasons.
AppDelegate methods like applicationWillTerminate()
will also be called when you manually kill the app.
However, a hacky way would be to monitor the iPhone's battery level. There is an API for that, you can even use NotificationCenter
to be notified on each battery level change.
Then, if applicationWillTerminate()
is called and battery is empty, the phone is definitely shutting down.
But, please not that battery drain is probably the most common way of shutting iPhone, but not the only one, since user can always shut down or restart the iPhone manually.
If anyone is interested in monitoring battery status, here is how.
Upvotes: 0
Reputation: 1045
Had to test it.
applicationWillResignActive
will be called once you hold power for shut down and you have option to swipe.
If you swipe to shutdown applicationDidEnterBackground
will be called then applicationWillTerminate
.
Maybe try not to use breakpoint but print to test.
But not sure how to know if it is regular closing of the app or shutdown.
Upvotes: 5