Swift: Natively Detect if App has Crashed

后端 未结 4 491
猫巷女王i
猫巷女王i 2020-12-08 23:31

I have searched around, but have yet to find an answer that doesn\'t direct me towards a 3rd party service. I do not need anything intricate, just to save a value in N

4条回答
  •  醉话见心
    2020-12-09 00:08

    FirebaseCrashlytics

    If you don't use Fabric because it is deprecated, You need to use following code in your ViewController that was mentioned in Updagte to the Firebase Crashlytics SDK.

    I use it like this:

    // 1. import Crashlytics
    import FirebaseCrashlytics
    
    class YOUR_ROOT_VIEW_CONTROLLER {
    
       override viewDidLoad(){
           //...
    
           // 2. register to get the notifications
           self.configCrashlytics()
    
           // ...
       }
    
        func configCrashlytics() {
            /* You must set setCrashlyticsCollectionEnabled to false in order to use
            checkForUnsentReportsWithCompletion. */
    
            Crashlytics.crashlytics().setCrashlyticsCollectionEnabled(false)
    
            Crashlytics.crashlytics().checkForUnsentReports { hasUnsentReport in
              let hasUserConsent = false
              // ...get user consent.
    
              if hasUserConsent && hasUnsentReport {
                Crashlytics.crashlytics().sendUnsentReports()
              } else {
                Crashlytics.crashlytics().deleteUnsentReports()
              }
            }
    
            // Detect when a crash happens during your app's last run.
            if Crashlytics.crashlytics().didCrashDuringPreviousExecution() {
              // ...notify the user.
                DispatchQueue.main.async {
                    let alert = Utils.shared.errorAlert(title: "Sorry!", message: "This App was crashed during last run")
                    self.present(alert, animated: true, completion: nil)
                }
            }
            
        }
        // 4. Add a button that run fatallError()
        @IBAction func crashApp(_ sender: UIButton) {
            fatalError()
        }
    }
    
    

提交回复
热议问题