捕获系统异常崩溃的方法

1、使用PLCrashReporter框架

PLCrashReporterConfig *config = [[PLCrashReporterConfig alloc] initWithSignalHandlerType:PLCrashReporterSignalHandlerTypeMach symbolicationStrategy:PLCrashReporterSymbolicationStrategyAll];
    
    PLCrashReporter *reporter = [[PLCrashReporter alloc] initWithConfiguration:config];
    NSData *data = [reporter generateLiveReport];

    PLCrashReport *report = [[PLCrashReport alloc] initWithData:data error:nil];
    
    NSString *reportStr = [PLCrashReportTextFormatter stringValueForCrashReport:report withTextFormat:PLCrashReportTextFormatiOS];
 
    NSLog(@"%@", reportStr);

 2、使用系统NSSetUncaughtExceptionHandler方法

如果同时有多方通过NSSetUncaughtExceptionHandler注册异常处理程序,和平的作法是:后注册者通过NSGetUncaughtExceptionHandler将先前别人注册的handler取出并备份,在自己handler处理完后自觉把别人的handler注册回去,规规矩矩的传递。不传递强行覆盖的后果是,在其之前注册过的日志收集服务写出的Crash日志就会因为取不到NSException而丢失Last Exception Backtrace等信息。(P.S. iOS系统自带的Crash Reporter不受影响)

NSUncaughtExceptionHandler *handler;
-(void)viewDidLoad
{
    //取出之前的NSUncaughtExceptionHandler
    handler = NSGetUncaughtExceptionHandler();
    
    //捕获exception
    NSSetUncaughtExceptionHandler(uncaughtExceptionHandler);    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //数组越界,产生崩溃
    NSArray *arr = @[@"aaa", @"bbb"];
    NSLog(@"%@", arr[3]);
}

void uncaughtExceptionHandler(NSException *exception)
{
    //获取崩溃信息,
    NSLog(@"%@, %@, %@", exception.name, exception.reason, exception.userInfo);
    NSSetUncaughtExceptionHandler(handler);
}

输出:
NSRangeException, *** -[__NSArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 1], (null)

 

参考文章:

http://www.cocoachina.com/ios/20150701/12301.html

http://www.jianshu.com/p/930d7f77df6c

转载于:https://my.oschina.net/mexiaobai1315/blog/1557321

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值