iOS--应用异常捕获

#import

@interface CatchCrash : NSObject

void uncaughtExceptionHandler(NSException *exception); 

@end


-------------

#import "CatchCrash.h"

@implementation CatchCrash

void uncaughtExceptionHandler(NSException *exception)

{


  // 异常的堆栈信息


  NSArray *stackArray = [exception callStackSymbols];


  // 出现异常的原因


  NSString *reason = [exception reason];


  // 异常名称


  NSString *name = [exception name];


  NSString *exceptionInfo = [NSString stringWithFormat:@"Exception reason:%@\nException name:%@\nException stack:%@",name?name:@"", reason?reason:@"", stackArray?stackArray:@[@""]];



  NSMutableArray *tmpArr = [NSMutableArray arrayWithArray:stackArray];


  [tmpArr insertObject:reason atIndex:0];


  //保存到本地  --  下次启动的时候,上传这个log

  NSString*cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) firstObject];

  // 实例化NSDateFormatter

  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

  // 设置日期格式

  [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

  // 获取当前日期

  NSDate *currentDate = [NSDate date];

  NSString *currentDateString = [formatter stringFromDate:currentDate];

  NSTimeInterval time = [currentDate timeIntervalSinceDate:[PCUtil getAppLauchTime]];

    NSString* useTime=[NSString stringWithFormat:@"%d",(int)time];

  NSString *documnetPath = [cachesDir stringByAppendingPathComponent:@"ErrorDic.plist"];

//    PCLoginSession *session = [PCUtil loginSession];

    NSString*flag;

  if([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {

      flag=@"1";

  }else if([UIApplication sharedApplication].applicationState == UIApplicationStateBackground){

      flag=@"0";

  }else{

      flag=@"";

  }

//准备要存入的字典

  NSDictionary *errDic = @{


                             @"flag":flag,


                            @"exceptionInfo":exceptionInfo

                            };


  //将字典存入指定的本地文件

  [errDic writeToFile:documnetPath atomically:YES];

}


使用在appDelegate里面

//注册消息处理函数的处理方法

    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);


    //上次异常闪退信息上传

    double seconds = 3.0;

    dispatch_time_t postTime = dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC);

    dispatch_after(postTime, dispatch_get_main_queue(), ^(void){

//上传服务端

    });

你可能感兴趣的:(iOS--应用异常捕获)