ios crash日志上传服务器

2019-03-28  本文已影响0人  扛支枪
NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
void UncaughtExceptionHandler(NSException *exception){
    NSArray *callStackArr = [exception callStackSymbols];
    NSString *reason = [exception reason];
    NSString *name = [exception name];
    NSMutableString *strSymbols = [NSMutableString string];
    
    for (int i = 0; i < callStackArr.count; i ++) {
        [strSymbols appendString:callStackArr[i]];
        [strSymbols appendString:@"\r\n"];
    }
    
    UIDevice *device = [UIDevice currentDevice];
    NSString *deInfo = [NSString stringWithFormat:@"%@,%@%@",
                        device.model,device.systemName,device.systemVersion];
    
    NSString *filePath = [NSHomeDirectory()
                          stringByAppendingPathComponent:@"Library/Caches/ExceptionLog"];
    NSString *crashString = [NSString stringWithFormat:@"DeviceInfo:%@\nExceptionName:%@\nExceptionReason:%@\nExceptionCallStackInfo:%@",deInfo,name,reason,strSymbols];
    [crashString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"崩溃详情CRASH: %@", exception);
    NSLog(@"崩溃详情Stack Trace: %@",[exception callStackSymbols]);
    [[CrashLogSender shareInstance] sendCrashLog:crashString];
}
@implementation CrashLogSender
+ (instancetype)shareInstance{
    static CrashLogSender *crashLog;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        crashLog = [[CrashLogSender alloc] init];
    });
    return crashLog;
}
// 通过post 或者 get 方式来将异常信息发送到服务器
- (void)sendCrashLog:(NSString *)crashLogDic {
    dispatch_semaphore_t semophore = dispatch_semaphore_create(0); // 创建信号量
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:nil delegateQueue:nil];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"你的上传日志的地址"]];
    [request setHTTPMethod:@"POST"];
    NSString *requestString = [NSString stringWithFormat:@"machine_code=11111111&crash_log=%@",crashLogDic];
    request.HTTPBody = [requestString dataUsingEncoding:NSUTF8StringEncoding];
    [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"response%@",response);
        dispatch_semaphore_signal(semophore); // 发送信号

    }] resume];
    dispatch_semaphore_wait(semophore, DISPATCH_TIME_FOREVER); // 等待
}
上一篇 下一篇

猜你喜欢

热点阅读