1,AppDelegate中记录日志和异常信息
#pragma mark --------test method(save LogInfo to File)--------
- (void)redirectNSlogToDocumentFolder
{
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"LogInfo.log"];
NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+", stdout);
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+", stderr);
}
void UncaughtExceptionHandler(NSException *exception) {
NSArray *arr = [exception callStackSymbols];//得到当前调用栈信息
NSString *reason = [exception reason];//非常重要,就是崩溃的原因
NSString *name = [exception name];//异常类型
DEBUGLOG(@"********************************** start record crash log **************************************");
DEBUGLOG(@"exception type : %@ \n crash reason : %@ \n call stack info : %@", name, reason, arr);
DEBUGLOG(@"********************************** end record crash log **************************************");
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//These code will cause that logInfo is saved to File
UIDevice *device = [UIDevice currentDevice];
if (![[device model]isEqualToString:@"iPad Simulator"]) {
NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);//记录异常
[self redirectNSlogToDocumentFolder];//将NSLog信息重定向到文件
}
//后面的代码省略
}
2,发送邮件:
Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
if (mailClass != nil){
// We must always check whether the current device is configured for sending emails
if([mailClass canSendMail]){
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"LogInfo.log"];//注意不是NSData!
NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];
NSURL *fileUrl = [NSURL fileURLWithPath:logFilePath];
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;//自己实现代理
[picker setToRecipients:@[EmailHost]];//邮箱地址
[picker setSubject:NSLocalizedString(@"EmailSubject", nil)];//邮件主题
[picker addAttachmentData:[NSData dataWithContentsOfURL:fileUrl] mimeType:@"" fileName:@"LogInfo.log"];
NSString *content=NSLocalizedString(@"EmailContent", nil);//邮件正文
[picker setMessageBody:content isHTML:NO];
[self presentViewController:picker animated:YES completion:^{
//DEBUGLOG(@"------");
}];
}else{
//SHOW_ALERT(NSLocalizedString(@"EmialNoAccount", @"Your device has not been configured email account."));
}
}else{
//SHOW_ALERT(NSLocalizedString(@"EmialUnSupport", @"Your device does not support email."));
}