Swift 使用NSSetUncaughtExceptionHandler 实现异常捕获及日志上传和app 起死回生

Swift 使用NSSetUncaughtExceptionHandler 实现异常捕获及日志上传和app 起死回生,第1张

       App 闪退对于开发人员来说比较头疼,对异常的捕获和定位,以便快速修复Bug 非常考验一个人的功底。对于iOS系统来说通过使用Runtime 和 扩展 来处理异常并友好的提示不让其闪退是不错的选择,但是比较繁琐。好在系统提供了一个 NSSetUncaughtExceptionHandler api 能捕获所有异常。今天主要介绍该函数在Swift 中的使用。先看下效果图:

1、定义异常捕获及处理的相关方法。

本代码参考了 https://github.com/lbwxly/CrashHandler 这篇博客,由于没使用NSSetUncaughtExceptionHandler 所以经测试效果不太令人满意

import Foundation

public typealias Completion = ()->Void;
public typealias CrashCallback = (String,Completion)->Void;

public var crashCallBack: CrashCallback?

func signalHandler(signal:Int32) -> Void {
    let stackTrace = Thread.callStackSymbols.joined(separator: "\r\n")
    crashCallBack?(stackTrace,{
        unregisterSignalHandler();
        exit(signal);
    });
}

func registerSignalHanlder()
{
    objc_setUncaughtExceptionHandler { (_response:Any?) in
        if let signal = _response as? Int32 {
            signalHandler(signal: signal)
        }
        else if let exception = _response as? NSException {
            //            print("++++++++++++++++++ 异常信息 ++++++++++++++++++")
            //            NSLog("name:%@",exception.name.rawValue)
            //            NSLog("reason:%@",exception.reason ?? "--")
            //            NSLog("userInfo:%@",exception.userInfo ?? [:])
            //            NSLog("Stack Trace:%@",exception.callStackSymbols)
            //            NSLog("Stack ReturnAddresses:\n%@", exception.callStackReturnAddresses)
            //            NSLog("Exception All:\n%@", exception)
            crashCallBack?(exception.reason ?? exception.callStackSymbols.joined(separator: "\r\n"),{
                unregisterSignalHandler();
                exception.raise()
            });
        }
    }
    
    signal(SIGINT,  signalHandler);
    signal(SIGSEGV, signalHandler);//野指针,僵尸对象
    signal(SIGTRAP, signalHandler);
    signal(SIGABRT, signalHandler);
    signal(SIGILL,  signalHandler);
    signal(SIGBUS,  signalHandler);
    signal(SIGFPE,  signalHandler);
    signal(SIGTERM, signalHandler);
    signal(SIGKILL, signalHandler);//CPU无法执行的代码(比如无效指令、除以0等)
    signal(SIGPIPE, signalHandler);
}

func unregisterSignalHandler()
{
    signal(SIGINT,  SIG_DFL);
    signal(SIGSEGV, SIG_DFL);
    signal(SIGTRAP, SIG_DFL);
    signal(SIGABRT, SIG_DFL);
    signal(SIGILL,  SIG_DFL);
    signal(SIGBUS,  SIG_DFL);
    signal(SIGFPE,  SIG_DFL);
    signal(SIGTERM, SIG_DFL);
    signal(SIGKILL, SIG_DFL);
    signal(SIGPIPE, SIG_DFL);
}

public class CrashHandler
{
    public static func setup(callBack:@escaping CrashCallback){
        crashCallBack = callBack;
        registerSignalHanlder();
    }
}

2、调用 

didFinishLaunchingWithOptions是全局的方法,所以在此注册调用,能捕获所有异常

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        //输出异常日志
        CrashHandler.setup {[weak self] (stackTrace, completion) in
            self?.showExceptionFor(Reason: stackTrace)
            completion()
        }
        
        return true
    }
}

3、捕获异常后的处理

可以返回到主页或者上传日志到服务器,具体 *** 作可以自由发挥

//MARK: - 异常处理
extension AppDelegate {
    
    private func showExceptionFor(Reason reason:String,
                                  andTitle t:String = "app异常"){
        
        //var dismiss = false
        let currentRunloop = CFRunLoopGetCurrent()
        
        if let vc = UIApplication.shared.keyWindow?.rootViewController {
            Utils.shareInstance().showBoxFor(ViewController: vc,
                                             andMessage: t,
                                             andOK: "提交日志,并返回首页",
                                             andOKBlock: {[weak self] action in
                print("异步提交异常日志")
                //...
                
                //返回首页
                var arr = self?.navController.popToRootViewController(animated: false)
                Utils.shareInstance().gotoRoot(ViewController: arr)
                arr?.removeAll()
                //dismiss = true
            },
                                             andCancle: nil,
                                             withInfo: reason)
        }
        
        if let arrModes = CFRunLoopCopyAllModes(currentRunloop) as? Array {
            //while !dismiss {
            while true {
                for model in arrModes {
                    CFRunLoopRunInMode(CFRunLoopMode.init(rawValue: model), 0.001, false)
                }
            }
        }
    }
}

由于调用 popToRootViewController方法导致了内存泄露,暂时还没好的办法处理

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/993353.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存