iOS 原生的崩溃日志收集与发送三

AppDelegate中使用抓捕异常监听,保存文件,在下一次打开程序时将异常文件发送到自己的服务器

AppDelegate.h

#import "AppDelegate.h"
#import "MyCrashExceptionHandler.h"
#import "NSMutableURLRequest+PostFile.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

#pragma mark -- 崩溃日志
    [MyCrashExceptionHandler setDefaultHandler];
    // 发送崩溃日志
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *dataPath = [path stringByAppendingPathComponent:@"Exception.txt"];
    NSData *data = [NSData dataWithContentsOfFile:dataPath];
    if (data != nil) {
        [self sendExceptionLogWithData:data path:dataPath];
    }

    return YES;
}

#pragma mark -- 发送崩溃日志
- (void)sendExceptionLogWithData:(NSData *)data path:(NSString *)path {
    NSLog(@"sendExceptionLogWithData");
    NSMutableString *filename = [NSMutableString string];
    [filename appendString:[self currentTimeStr]];
    //[filename appendString:@"用户ID"];// 作为唯一的标示
    [filename appendString:@".txt"];
    [self PostFileWithUrl:[NSString stringWithFormat:@"上传文件的接口"] path:path fileName:filename];
}


-(void)PostFileWithUrl:(NSString *)remoteUrl path:(NSString *)path fileName:(NSString *)filename{
    //用post上传文件

    //url
    NSURL *url=[NSURL URLWithString:remoteUrl];
    //post请求
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url andFileName:filename andLocalFilePath:path andParams:@{@"params" : @"{'account':'*******', 'password':'******'}"}]; // Params:POST的普通参数部分

    //连接(NSURLSession)
    NSURLSession *session=[NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        NSLog(@"response--1111-%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
         NSFileManager *fileManager = [NSFileManager defaultManager];
        // 删除崩溃日志
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *dataPath = [path stringByAppendingPathComponent:@"Exception.txt"];
        [fileManager removeItemAtPath:dataPath error:nil];
    }];
    [dataTask resume];
}

//获取当前时间戳
- (NSString *)currentTimeStr{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒,不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

@end

你可能感兴趣的:(iOS 原生的崩溃日志收集与发送三)