使用 NSSetUncaughtExceptionHandler 方法,將異常信息寫入日志文件。
首先新加一個類 DSQCrashCatch ,.h中定義方法:
+ (void)catchCrash;
在 didFinishLaunchingWithOptions 中設(shè)置該方法:
[DSQCrashCatch?catchCrash]
@implementation DSQCrashCatch
void uncaughtExceptionHandler(NSException * exception);
+ (void)catchCrash {
? ? staticdispatch_once_tonceToken;
? ? dispatch_once(&onceToken, ^{
? ? ? ? NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
? ? });
}
void uncaughtExceptionHandler(NSException * exception){
? ? //獲取系統(tǒng)當前時間,(注:用[NSDate date]直接獲取的是格林尼治時間,有時差)
? ? NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
? ? [formattersetDateFormat:@"yyyy-MM-dd HH:mm:ss"];
? ? NSString*crashTime = [formatterstringFromDate:[NSDatedate]];
? ? [formattersetDateFormat:@"HH-mm-ss"];
? ? NSString*crashTimeStr = [formatterstringFromDate:[NSDatedate]];
? ? [formattersetDateFormat:@"yyyyMMdd"];
? ? NSString*crashDate = [formatterstringFromDate:[NSDatedate]];
? ? //異常的堆棧信息
? ? NSArray*stackArray = [exceptioncallStackSymbols];
? ? //出現(xiàn)異常的原因
? ? NSString*reason = [exceptionreason];
? ? //異常名稱
? ? NSString*name = [exceptionname];
? ? //拼接錯誤信息
? ? NSString *exceptionInfo = [NSString stringWithFormat:@"CrashTime: %@\nException reason: %@\nException name: %@\nException call stack:%@\n", crashTime, name, reason, stackArray];
? ? //把錯誤信息保存到本地文件,設(shè)置errorLogPath路徑下
? ? //并且經(jīng)試驗,此方法寫入本地文件有效。
//? ? NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
? ? NSString*errorLogPath = [NSStringstringWithFormat:@"%@/CrashLogs/%@/",NSHomeDirectory(), crashDate];
? ? NSFileManager *manager = [NSFileManager defaultManager];
? ? if(![managerfileExistsAtPath:errorLogPath]) {
? ? ? ? [managercreateDirectoryAtPath:errorLogPath withIntermediateDirectories:true attributes:nil error:nil];
? ? }
? ? errorLogPath = [errorLogPathstringByAppendingFormat:@"%@.log",crashTimeStr];
? ? NSError*error =nil;
? ? NSLog(@"%@", errorLogPath);
? ? BOOLisSuccess = [exceptionInfowriteToFile:errorLogPathatomically:YESencoding:NSUTF8StringEncodingerror:&error];
? ? if(!isSuccess) {
? ? ? ? NSLog(@"將crash信息保存到本地失敗: %@", error.userInfo);
? ? }
}
@end