NSException

/**
 * 崩溃统计
 * 1.友盟
 * 2.Flurry
 * 3.Crashlytics
 */


/**
 * 拦截异常
 */
void handleException(NSException *exceptin)
{
    // 创建字典,存入异常信息
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    info[@"callStack"] = [exceptin callStackSymbols]; // 调用栈信息(错误来源于哪个方法)
    info[@"reason"] = [exceptin reason]; // 异常理由(错误描述)
    info[@"name"] = [exceptin name]; // 错误名称

    // 获取cache路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    // 拼接exception
     NSString *filePath = [cachePath stringByAppendingPathComponent:@"exception"];

    // 拼接时间串便于日后分析
    // 获得当前时间
    NSDate *date = [NSDate date];

    /*
    // 获取当前所在时区
    NSTimeZone *localZone = [NSTimeZone localTimeZone];

    // 获取时区所差秒数
    NSInteger second = [localZone secondsFromGMTForDate:otherDate];

    // 当前时间加上相差秒数获得准确时间
    NSDate *date = [[NSDate date] dateByAddingTimeInterval:second];
    */

    // 创建时间格式符
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    formatter.dateFormat = @"y-MM-dd HH-mm-ss";

    // 当前时间的字符串
    NSString *now = [formatter stringFromDate:date];

    NSLog(@"%@",now);
    NSLog(@"%@",cachePath);

    // 存入沙盒的文件名拼接时间
    NSString *newFilePath = [filePath stringByAppendingString:now];


    // 写入沙盒
    [info writeToFile:newFilePath atomically:YES];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
     // 下次用户启动程序的时候将沙盒中的错误信息传递给服务器



    // 捕捉异常信息
    NSSetUncaughtExceptionHandler(handleException);

    return YES;
}
  • 未处理
void handleException(NSException *exception)
{
    // C语言函数中要用UIApplication对象的代理才能调用里面的方法
    [[UIApplication sharedApplication].delegate performSelector:@selector(handle)];
}

- (void)handle
{

    NSLog(@"handle");
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"哈哈" message:@"傻逼了吧" preferredStyle:UIAlertControllerStyleAlert];


    [alertVc addAction:[UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

    }]];

    UIApplication *app = [UIApplication sharedApplication];


    [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSRunLoopCommonModes];
    [[NSRunLoop currentRunLoop] run];
}

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

    // 捕捉异常信息
    NSSetUncaughtExceptionHandler(handleException);

    return YES;
}

results matching ""

    No results matching ""