1. 程式人生 > >iOS 原生的崩潰日誌收集與傳送一

iOS 原生的崩潰日誌收集與傳送一

崩潰日誌工具類的建立

MyCrashExceptionHandler.h

#import <Foundation/Foundation.h>

@interface MyCrashExceptionHandler : NSObject

+ (void)setDefaultHandler;
+ (NSUncaughtExceptionHandler *)getHandler;
+ (void)TakeException:(NSException *) exception;

@end

MyCrashExceptionHandler.m

#import "MyCrashExceptionHandler.h"
// 沙盒的地址 NSString * applicationDocumentsDirectory() { return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; } // 崩潰時的回撥函式,將崩潰日誌的內容寫入到沙盒路徑 void UncaughtExceptionHandler(NSException * exception) { NSArray * arr = [exception callStackSymbols]; NSString
* reason = [exception reason]; // // 崩潰的原因 可以有崩潰的原因(陣列越界,字典nil,呼叫未知方法...) 崩潰的控制器以及方法 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]; } @implementation MyCrashExceptionHandler // 沙盒地址 - (NSString *)applicationDocumentsDirectory { return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; } + (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]; }