目前有很多方式获取app崩溃的信息。如 umeng、苹果自带itunesconnect等等
但也可以使用系统自带的NSSetUncaughtExceptionHandler。具体思路是,先将错误信息存储到app本地。等下次app启动时,将错误信息上传到服务器即可。
注册崩溃信息“方法”
//应用由系统启动后的入口
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *) launchOptions {
//收集崩溃信息
NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
...
}
崩溃信息获取方法实现
1.获取错误信息
2.设置文件名
3.设置路径
4.错误信息存储到文件
void uncaughtExceptionHandler(*exception){
//异常的堆栈信息
NSArray *stackArray = [exception callStackSymbols];
//出现异常的原因
NSString *reason=[exception reason];
//异常名称
NSString *name=[exception name];
NSString *exceptionInfo=[NSString stringWithFormat@"Exceptionreason:%@\nExceptionname %@\nExceptionstack%@",name,reason,stackArray];
//文件名是20160306-141723.txt
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYYMMdd-hhmmss"];
NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:ctime];
NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
NSString *fileName = [NSString stringWithFormat:@"%@.txt",confromTimespStr];
//存放LOG 信息的路径/Documents/ErrorLogs
NSString *logDocuments = [NSString stringWithFormat@"%@/Documents/ErrorLogs",NSHomeDirectory()];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir = FALSE;
BOOL isDirExist = [fileManager fileExistsAtPath:logDocuments isDirectory:&isDir];
if (!isDirExist || (isDirExist &&!isDir)){
//若没有此目录,则需先创建目录
[fileManager createDirectoryAtPath:[CatchCrash getErrorLogDocument] withIntermediateDirectories:YES attributes:nil error:nil];
}
//保存到本地
[exceptionInfo writeToFile:[NSString stringWithFormat:@"%@/%@",logDocuments,fileName] atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
上传日志文件
+ (void)sendLogFileToServer {
NSString *logDocuments = [NSString stringWithFormat:@"%@/Documents/ErrorLogs",NSHomeDirectory()];
//array 存储所有需要上传的日志文件
NSMutableArray* array = [[NSMutableArray alloc]init];
NSFileManager* fileMgr = [NSFileManager defaultManager];
NSArray* tempArray = [fileMgr contentsOfDirectoryAtPath:logDocuments error:nil];
//遍历文件夹
for (NSString* fileName in tempArray) {
BOOL flag = YES;
NSString* fullPath = [logDocuments stringByAppendingPathComponent:fileName];
if ([fileMgr fileExistsAtPath:fullPath isDirectory:&flag]) {
if(!flag) {
[array addObject:fullPath];
}
}
}
//我这里使用的是阿里云的OSS 接口
[Network initAppOSSClientCompletion:^(NSDictionary *response, NSString *remark,NSError *error) {
//初始化oss
if(error != nil) {
//出错
return;
}
if(remark.length == 0) {
for(NSString *filePath in array) {
//上传文件
[Network uploadErrorLogFile:filePath AccessKey<:response[kAcessKey] SecretKey:response[kSecretKey] BucketName:response[kBucketName] sucess:^(finished,NSError *error) {
if(finished) {
NSLog(@"上传文件成功:%@",filePath);
//上传文件成功后删除此文件
[fileMgr removeItemAtPath:filePath error:nil];
} else {
NSLog(@"上传文件失败");
}
}];
}
}
}];
}