I have been working on a game in swift and when the home button is tapped accidentally I would like to run a function that restarts the game. Does anyone know what code needs to be implemented to call a function when the home button is tapped and the app is closed. (by home button I mean the actual hardware button)
Asked
Active
Viewed 5,379 times
1
-
Do you want to know when your user leaves the app then? – ABakerSmith May 01 '15 at 14:32
-
Does it matter how the app is closed? – BSMP May 01 '15 at 14:33
-
no it does not matter how it is achieved as long as the app is closed – Zachary Stryczek May 01 '15 at 14:36
-
and yes I would like to know when the user leaves the app – Zachary Stryczek May 01 '15 at 14:41
1 Answers
8
You can use one of the following methods in your AppDelegate
// Taken straight from the AppDelegate template
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}

Allan Chau
- 693
- 1
- 5
- 15
-
-
1They should all be called. Check the Execution States for Apps section https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/TheAppLifeCycle/TheAppLifeCycle.html – Allan Chau Dec 22 '15 at 04:12