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
来源:oschina
链接:https://my.oschina.net/u/2615608/blog/1557321