上线的产品中,出现了bug一般都不能及时反馈给开发人员,因此需要在代码中添加异常监听,当程序崩溃时,及时上传错误报告。或者通过友盟第三方来添加错误报告。
1. 第三方统计【友盟】
更好的集成,方便开发者
2. AvoidCrash-github
避免常见的崩溃
设置为-fno-objc-arc
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
[AvoidCrash becomeEffective];
//监听通知:AvoidCrashNotification, 获取AvoidCrash捕获的崩溃日志的详细信息
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealwithCrashMessage:) name:AvoidCrashNotification object:nil];
return YES;
}
- (void)dealwithCrashMessage:(NSNotification *)note {
//注意:所有的信息都在userInfo中
//你可以在这里收集相应的崩溃信息进行相应的处理(比如传到自己服务器)
NSLog(@"%@",note.userInfo);
}
3. 自定义的捕捉异常
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
return YES;
}
void UncaughtExceptionHandler(NSException *exception){
// 异常日志获取
NSArray *excpArr = [exception callStackSymbols];
NSString *reason = [exception reason];
NSString *name = [exception name];
NSString *excpCnt = [NSString stringWithFormat:@"exceptionType: %@ \n reason: %@ \n stackSymbols: %@",name,reason,excpArr];
// 日常日志保存(可以将此功能单独提炼到一个方法中)
NSArray *dirArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dirPath = dirArr[0];
NSString *logDir = [dirPath stringByAppendingString:@"/CrashLog"];
BOOL isExistLogDir = YES;
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:logDir]) {
isExistLogDir = [fileManager createDirectoryAtPath:logDir withIntermediateDirectories:YES attributes:nil error:nil];
}
if (isExistLogDir) {
// 此处可扩展
NSString *logPath = [logDir stringByAppendingString:@"/crashLog.txt"];
[excpCnt writeToFile:logPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
}