需求
需要知道APP闪退的时候,到底发生了什么
解决
oc自带函数,可以监控到app发生异常
NSSetUncaughtExceptionHandler(&catchLog);
catchLog为C语言函数,传入函数指针,当发生异常时候,可以捕捉
走起
1.CatchLog.h 我使用了ASIHttpRequest
#import <Foundation/Foundation.h>
#import "ASIHTTPRequest.h"
@interface CatchLog : NSObject <ASIHTTPRequestDelegate>
+ (void)catchExceptionLog;
+ (void)uploadTheLog;
@end
CatchLog.m
#import "CatchLog.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
@implementation CatchLog
void catchLog(NSException *exception){
NSLog(@"捕捉到了异常");
NSArray *arr = [exception callStackSymbols];//得到当前调用栈信息
NSString *reason = [exception reason];//非常重要,就是崩溃的原因
NSString *name = [exception name];//异常类型
DDLogError(@"异常类型:%@",name);
DDLogError(@"崩溃原因:%@",reason);
DDLogError(@"栈信息:%@",arr);
//设置标志代表这次错误信息,需要下次打开APP时上传
[[NSUserDefaults standardUserDefaults] setObject:@YES forKey:@"isUploadLog"];
}
+ (void)catchExceptionLog{
NSSetUncaughtExceptionHandler(&catchLog);
}
#pragma mark --上传日志
+ (void)uploadTheLog{
NSURL *url = [NSURL URLWithString:@"http://myapp.tunnel.mobi/app/uploadLog"];
NSString *filePath = [[NSUserDefaults standardUserDefaults]objectForKey:@"logPath"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
// [request setValue:@"123" forKey:@"logContent"];
[request setPostValue:str forKey:@"logContent"];
// [request setFile:filePath forKey:@"logFile"];
// request.delegate = self;
// [request setDidFinishSelector:@selector(responseComplete)];
[request setCompletionBlock:^{
NSLog(@"上传成功");
}];
[request startSynchronous];
}
@end
filePath路径从本地取出,log日志具体可参参考上篇日志
2. 在AppDelegate中didFinishLaunchingWithOptions中,写入代码
[CatchLog catchExceptionLog];
3.测试代码可以使用
[NSDictionary dictionaryWithObject:nil forKey:nil];