蘋果雖然帶了崩潰日志的功能,但是估計沒幾個人會開啟允許,普通用戶根本就不知道所謂的開發(fā)者對自己有什么作用,還會擔心安全問題.所有我們還必須對程序進行一些處理,以獲取崩潰日志.本篇文章僅獲取了系統(tǒng)崩潰日志的打印,沒有對內(nèi)存方面進行進一步分析.
SDK提供了NSSetUncaughtExceptionHandler類,用來獲取系統(tǒng)的崩潰日志.我們通過捕獲崩潰日志并上傳到服務(wù)器,可以發(fā)現(xiàn)常見的的崩潰問題,特別是在項目緊張,缺少測試時間的時候可以提供很大的幫助.
通過定義UncaughtExceptionHandler類來捕獲并記錄崩潰日志.
#import "UncaughtExceptionHandler.h"
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 *baseMessage = [NSString stringWithFormat:@"IDENTIFIER_NUMBER: %@\n OSVERSION: %@\n PHONE_TYPE: %@\n APP_VERSION: %@", IDENTIFIER_NUMBER, PHONE_VERSION, PHONE_TYPE, APP_VERSION];
NSString *url = [NSString stringWithFormat:@"=============Crash Log=============\n%@\nname:\n%@\nreason:\n%@\ncallStackSymbols:\n%@", baseMessage,
name,reason,[arr componentsJoinedByString:@"\n"]];
NSString *path = [applicationDocumentsDirectory() stringByAppendingPathComponent:@"Exception.txt"];
[url writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
@implementation BPBUncaughtExceptionHandler
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
+ (void)setDefaultHandler {
NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);
}
@end
然后我們需要再定義一個CrashHandler類來將捕獲的崩潰日志上傳到后臺的服務(wù)器.上傳完成之后再刪除文件.
#import "CrashHandler.h"
@implementation BPBCrashHandler
+ (void)uploadCrashLog {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"Exception.txt"];
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
if (str) {
[ServerReqestUtils uploadCrashLogWithContent:str callBack:^(id obj) {
float code = [obj[@"code"] floatValue];
if (code == 1000) {
NSLog(@"上傳成功!");
[fileManager removeItemAtPath:filePath error:nil];
}
}];
}
}
@end
最后只需要在didFinishLaunchingWithOptions方法內(nèi)執(zhí)行這兩個方法就可以捕獲崩潰日志了.
[UncaughtExceptionHandler setDefaultHandler];
[CrashHandler uploadCrashLog];
文章整理參考網(wǎng)絡(luò)文章,如有錯誤,歡迎討論指出。