ios 异常捕获发送
1,- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions下添加
//安装异常捕获 #ifdef DEBUG [NSThread detachNewThreadSelector:@selector(startCatchException) toTarget:self withObject:nil]; #endif
2,
- (void)startCatchException { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self setCompileTime]; //保存错误日志 [CatchExceptionHandler setDefaultHandler]; [pool drain]; }
3,捕获异常类
.h
@interface CatchExceptionHandler : NSObject + (void)setDefaultHandler; + (NSUncaughtExceptionHandler *)getHandler; @end
.m
#import "CatchExceptionHandler.h" #import "ABServices.h" #define NSExceptionFile @"errorFile.txt" @implementation CatchExceptionHandler NSString *applicationDocumentsDirectory() { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES); NSString * documentsDirectory =[paths objectAtIndex:0]; return [documentsDirectory stringByAppendingPathComponent:NSExceptionFile]; } void UncaughtExceptionHandler(NSException *exception) { NSArray *arr = [exception callStackSymbols]; NSString *reason = [exception reason]; NSString *name = [exception name]; NSString *strTime =[ABServices getCurrentSysTime]; NSString *strError = [NSString stringWithFormat:@"\n\n\n=============异常崩溃报告=============\n当前版本的编译时间:\n%@\n崩溃发生的时间:\n %@\n崩溃名称:\n%@\n崩溃原因:\n%@\n堆栈信息:\n%@", [ABServices currentCompileTime],strTime,name,reason,[arr componentsJoinedByString:@"\n"]]; NSString *path = applicationDocumentsDirectory(); if ([[NSFileManager defaultManager]fileExistsAtPath:path]) { NSString *lasterror = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; strError = [NSString stringWithFormat:@"%@%@", lasterror, strError]; [lasterror release]; } [strError writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil]; NSMutableString *mailUrl = [[[NSMutableString alloc]init]autorelease]; //添加收件人 NSArray *toRecipients = [NSArray arrayWithObjects: @"a@b.com", @"a@a.com",nil]; [mailUrl appendFormat:@"mailto:%@", [toRecipients componentsJoinedByString:@","]]; //添加抄送 NSArray *ccRecipients = [NSArray arrayWithObjects:@"e@e.com" ,nil]; [mailUrl appendFormat:@"?cc=%@", [ccRecipients componentsJoinedByString:@","]]; //添加密送 NSArray *bccRecipients = [NSArray arrayWithObjects:@"", nil]; [mailUrl appendFormat:@"&bcc=%@", [bccRecipients componentsJoinedByString:@","]]; [mailUrl appendString:@"&subject=崩溃日志"]; //添加邮件内容 [mailUrl appendString:[NSString stringWithFormat:@"&body=%@", strError]]; NSString* email = [mailUrl stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; //#ifdef _DEBUG_LOG_ [[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]]; //#endif } + (void)setDefaultHandler { NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler); } + (NSUncaughtExceptionHandler*)getHandler { return NSGetUncaughtExceptionHandler(); } @end