quit an app in swift

To quit an app in Swift, you can use the exit(0) function. This terminates the app immediately, without any further cleanup or processing.

However, it is generally recommended that you do not use this function, as it may leave your app in an inconsistent state and cause issues for users. Instead, you should use the standard iOS navigation patterns and let the user exit the app themselves.

Here is an example of how to use the exit() function in Swift:

main.swift
func quitApp() {
    exit(0)
}
31 chars
4 lines

Again, it is not recommended that you use this function in your app. Instead, you can use standard UI components to allow the user to exit the app gracefully. For example, you can use a UIAlertController to prompt the user to confirm that they want to quit the app, then use the UIApplication.sharedApplication().terminate() method to exit the app:

main.swift
func quitApp() {
    let alertController = UIAlertController(title: "Confirm Exit", message: "Are you sure you want to quit the app?", preferredStyle: .alert)
    
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    alertController.addAction(cancelAction)
    
    let confirmAction = UIAlertAction(title: "Quit", style: .default) { _ in
        UIApplication.sharedApplication().terminate()
    }
    alertController.addAction(confirmAction)
    
    present(alertController, animated: true, completion: nil)
}
548 chars
14 lines

related categories

gistlibby LogSnag