在iOS程序崩潰時,一般我們是用Bugtags、Bugly、友盟等第三方收集崩潰,其實官方提供的NSUncaughtExceptionHandler來收集crash信息。實現(xiàn)方式如下:
自定義一個UncaughtExceptionHandler類,在.h中:
@interface CustomUncaughtExceptionHandler : NSObject
+ (void)setDefaultHandler;
+ (NSUncaughtExceptionHandler *)getHandler;
@end
在.m中實現(xiàn):
#import "CustomUncaughtExceptionHandler.h"
// 沙盒的地址
NSString * applicationDocumentsDirectory() {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
// 崩潰時的回調(diào)函數(shù)
void UncaughtExceptionHandler(NSException * exception) {
NSArray * arr = [exception callStackSymbols];
NSString * reason = [exception reason]; // // 崩潰的原因 可以有崩潰的原因(數(shù)組越界,字典nil,調(diào)用未知方法...) 崩潰的控制器以及方法
NSString * name = [exception name];
NSString * url = [NSString stringWithFormat:@"crash報告\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[arr componentsJoinedByString:@"\n"]];
NSString * path = [applicationDocumentsDirectory() stringByAppendingPathComponent:@"crash.txt"];
// 將一個txt文件寫入沙盒
[url writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
@implementation CustomUncaughtExceptionHandler
+ (void)setDefaultHandler {
NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
}
+ (NSUncaughtExceptionHandler *)getHandler {
return NSGetUncaughtExceptionHandler();
}
@end
這樣我們就實現(xiàn)好了一個自定義UncaughtExceptionHandler類,接下來只需要在合適的地方獲取crash文件以及傳到服務(wù)器上去即可,如下所示:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//崩潰日志
[CustomUncaughtExceptionHandler setDefaultHandler];
//獲取崩潰日志,然后發(fā)送
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *dataPath = [path stringByAppendingPathComponent:@"crash.txt"];
NSData *data = [NSData dataWithContentsOfFile:dataPath];
if (data != nil) {
//發(fā)送崩潰日志
NSLog(@"crash了:%@",data);
}
}
推薦閱讀:
iOS面試匯總含面經(jīng),面試講解面試題等欄目持續(xù)更新
作者:溫潤如玉盧三哥
鏈接:https://juejin.cn/post/6953142642746064910