ios Swift:本地检测App是否崩溃

3b6akqbq  于 2023-08-08  发布在  iOS
关注(0)|答案(4)|浏览(199)

我四处寻找,但还没有找到一个答案,不指导我对第三方服务。我不需要任何复杂的东西,只是为了保存一个值在NSUserDefaults,所以当应用程序打开下一个,我可以显示一个警告,说应用程序已经崩溃。

  • 谢谢-谢谢
ycl3bljg

ycl3bljg1#

多亏了@RyanCollins的帮助,我自己解决了这个问题。App Delegate中的函数applicationWillTerminate仅在应用程序正确关闭时运行。原生检测应用崩溃的代码如下所示。

全局定义变量

let crashedNotificationKey = "com.stackoverflow.crashNotificationKey"
var crashedLastTime = true

字符串

应用委托

func applicationWillTerminate(application: UIApplication) {
    crashedLastTime = false
    prefs.setBool(crashedLastTime, forKey: "crash")
}

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    crashedLastTime = prefs.boolForKey("crash")
    if crashedLastTime == true {

        crashedLastTime = false
        prefs.setBool(crashedLastTime, forKey: "crash")
        NSNotificationCenter.defaultCenter().postNotificationName(crashedNotificationKey, object: self)

    } else {

        crashedLastTime = true
        prefs.setBool(crashedLastTime, forKey: "crash")

    }

    return true
}

根视图控制器

override func awakeFromNib() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "crashedAlert", name: crashedNotificationKey, object: nil)
}

func crashedAlert() {
    let alert = UIAlertController(title: "The app has crashed!", message: "Sorry about that! I am just a 17 year old highschooler making my first game!", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "It's cool bro.", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}

xwbd5t1u

xwbd5t1u2#

详细数据

  • Swift 4.2
  • Xcode 10.1(10B61)

方案一

https://github.com/zixun/CrashEye/blob/master/CrashEye/Classes/CrashEye.swift

溶液1全样

!不要忘记复制(或安装POD)解决方案代码!!!

AppDelegate.swift

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        CrashEye.add(delegate: self)
        return true
    }
}

extension AppDelegate: CrashEyeDelegate {
    func crashEyeDidCatchCrash(with model: CrashModel) {
        UserDefaults.standard.set(model.reason + "(\(Date()))", forKey: "crash")
    }
}

字符串
ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton(frame: CGRect(x: 40, y: 40, width: 80, height: 44))
        button.setTitle("BOOOM", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.addTarget(self, action: #selector(boomButtonTouchedUpInside), for: .touchUpInside)
        view.addSubview(button)
    }

    override func viewDidAppear(_ animated: Bool) {
        if let date = UserDefaults.standard.string(forKey: "crash") {
            let alert = UIAlertController(title: "", message: date, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
            present(alert, animated: true)
        }
    }

    @objc func boomButtonTouchedUpInside(_ sender: Any) {
        let arr = [1, 2, 3]
        let elem = arr[4]
    }
}

解决方案2. Crashlytics

Install Crashlytics

溶液2全样品

AppDelegate.swift

import UIKit
import Fabric
import Crashlytics

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        Crashlytics.sharedInstance().delegate = self
        Fabric.with([Crashlytics.self])
        return true
    }
}

extension AppDelegate: CrashlyticsDelegate {
    func crashlyticsDidDetectReport(forLastExecution report: CLSReport) {
        let alert = UIAlertController(title: "\(report.dateCreated)", message: report.identifier, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        DispatchQueue.global(qos: .background).async {
            sleep(3)
            DispatchQueue.main.async {
                self.window?.rootViewController?.present(alert, animated: true)
            }
        }
    }
}


ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton(frame: CGRect(x: 40, y: 40, width: 80, height: 44))
        button.setTitle("BOOOM", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.addTarget(self, action: #selector(boomButtonTouchedUpInside), for: .touchUpInside)
        view.addSubview(button)
    }

    @objc func boomButtonTouchedUpInside(_ sender: Any) {
        let arr = [1, 2, 3]
        let elem = arr[4]
    }
}

结果

1.启动应用程序
1.按下“Booom”按钮(应用程序将崩溃)
1.又是午餐app
x1c 0d1x的数据

omhiaaxx

omhiaaxx3#

问题是,如果应用程序崩溃,那么它就无法运行代码来写入NSUserDefaults。
我所知道的最好的解决方案是使用PLCrashReporter(https://plcrashreporter.org

83qze16e

83qze16e4#

FirebaseCrashlytics

如果您不使用Fabric,因为它已被弃用,您需要在您的ViewController中使用以下代码,这些代码在Firebase Crashlytics SDK的更新中提到。
我是这样用的:

// 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 that last time the app crashed
          
        }
        
    }
    // 4. Add a button that run fatallError()
    @IBAction func crashApp(_ sender: UIButton) {
        fatalError()
    }
}

字符串

相关问题