1

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)

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

1 Answers1

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
  • which one of these gets called when the user presses the home button? – DrZ214 Dec 21 '15 at 02:28
  • 1
    They 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