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

       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<CFString> {
            //while !dismiss {
            while true {
                for model in arrModes {
                    CFRunLoopRunInMode(CFRunLoopMode.init(rawValue: model), 0.001, false)
                }
            }
        }
    }
}

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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追夢秋陽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值