Proper way to exit iPhone application?

前端 未结 25 2691
难免孤独
难免孤独 2020-11-22 01:54

I am programming an iPhone app, and I need to force it to exit due to certain user actions. After cleaning up memory the app allocated, what\'s the appropriate method to ca

25条回答
  •  爱一瞬间的悲伤
    2020-11-22 02:55

    You should not directly call the function exit(0) as it will quit the application immediately and will look like your app is crashed. So better to show users a confirmation alert and let them do this themselves.

    Swift 4.2

    func askForQuit(_ completion:@escaping (_ canQuit: Bool) -> Void) {
        let alert = UIAlertController(title: "Confirmation!", message: "Do you want to quit the application", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: { (action) in
            alert.dismiss(animated: true, completion: nil)
            completion(true)
        }))
        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.cancel, handler: { (action) in
            alert.dismiss(animated: true, completion: nil)
            completion(false)
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    /// Will quit the application with animation
    func quit() {
        UIApplication.shared.perform(#selector(NSXPCConnection.suspend))
        /// Sleep for a while to let the app goes in background
        sleep(2)
        exit(0)
    }
    

    Usage:

    self.askForQuit { (canQuit) in
         if canQuit {
             self.quit()
         }
    }
    

提交回复
热议问题