實在是不知道該寫點什么,就寫下如何記錄程序的Crash吧。
原理很簡單,就是創建一個Crash的管理對象,然后記錄錯誤,每次啟動的時候判斷是否有錯誤記錄,如果有錯誤記錄就處理錯誤記錄。下面是具體實現過程:
1.創建一個NSobject對象
.h文件中寫三個方法:
+ (void)setDefaultHandler;
+ (NSUncaughtExceptionHandler *)getHandler;
+ (void)TakeException:(NSException *) exception;
.m文件中進行實現:
// 沙盒的地址
NSString * applicationDocumentsDirectory() {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
// 崩潰時的回調函數
void UncaughtExceptionHandler(NSException * exception) {
NSArray * arr = [exception callStackSymbols];
NSString * reason = [exception reason]; // // 崩潰的原因
NSString * name = [exception name];
NSString * url = [NSString stringWithFormat:@"========異常錯誤報告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[arr componentsJoinedByString:@"\n"]];
NSString * path = [applicationDocumentsDirectory() stringByAppendingPathComponent:@"Exception.txt"];
// 將一個txt文件寫入沙盒
[url writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
+ (void)setDefaultHandler {
NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
}
+ (NSUncaughtExceptionHandler *)getHandler {
return NSGetUncaughtExceptionHandler();
}
+ (void)TakeException:(NSException *)exception {
NSArray * arr = [exception callStackSymbols];
NSString * reason = [exception reason];
NSString * name = [exception name];
NSString * url = [NSString stringWithFormat:@"========異常錯誤報告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[arr componentsJoinedByString:@"\n"]];
NSString * path = [applicationDocumentsDirectory() stringByAppendingPathComponent:@"Exception.txt"];
[url writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
2.每次啟動程序的時候判斷是否有錯誤記錄,如果有就處理,處理后刪除文件
didFinishLaunchingWithOptions
方法中實現:
[CrashLogUpdate setDefaultHandler];
// 查看是否有奔潰日志
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *dataPath = [path stringByAppendingPathComponent:@"Exception.txt"];
NSData *data = [NSData dataWithContentsOfFile:dataPath];
if (data != nil) {
[self sendExceptionLogWithData:data path:dataPath];
}
sendExceptionLogWithData
處理并刪除:
NSString * string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",string);
// 刪除文件
NSFileManager *fileManger = [NSFileManager defaultManager];
[fileManger removeItemAtPath:path error:nil];
以上兩部就實現了全部過程,很簡單,現在也有很多第三方庫,并且還用了Swizzle來記錄用戶的操作步驟,還對crash進行了分析,給出了建議的解決方案等等超多功能,智能的不要不要的,我們就可以不用再造輪子了,拿來用吧-
demo點擊下載