iOS崩潰日志 收集與發(fā)送服務器

iOS開發(fā)中我們會遇到程序拋出異常退出的情況,如果是在調試的過程中,異常的信息是一目了然,我們可以很快的定位異常的位置并解決問題。那么當應用已經打包,iPhone設備通過ipa的包安裝應用后,在使用過程發(fā)現crash,那么如何獲取crash日志呢?對于保密性要求不高的程序來說,也可以選擇各種一條龍Crash統(tǒng)計產品,如 Crashlytics,Hockeyapp ,友盟,Bugly 等等,不過IOS SDK中提供了一個現成的函數 NSSetUncaughtExceptionHandler 用來做異常處理
利用NSSetUncaughtExceptionHandler,當程序異常退出的時候,可以先進行處理,然后做一些自定義的動作,并通知開發(fā)者,是大多數軟件都選擇的方法。下面就介紹如何在iOS中實現:

首先創(chuàng)建一個MyUncaughtExceptionHandler類 (名字可以自己起)實現崩潰時調用的函數,下面我粘貼我程序中的完整代碼,你們需要用的時候可以直接復制就可以.

#import <Foundation/Foundation.h>
// 崩潰日志
@interface MyUncaughtExceptionHandler : NSObject

+ (void)setDefaultHandler;
+ (NSUncaughtExceptionHandler *)getHandler;
+ (void)TakeException:(NSException *) exception;

end
#import "MyUncaughtExceptionHandler.h"
#import "AFNetworking.h"
// 沙盒的地址
NSString * applicationDocumentsDirectory() {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

// 崩潰時的回調函數
void UncaughtExceptionHandler(NSException * exception) {
    NSArray * arr = [exception callStackSymbols];
    NSString * reason = [exception reason]; // // 崩潰的原因  可以有崩潰的原因(數組越界,字典nil,調用未知方法...) 崩潰的控制器以及方法
    NSString * name = [exception name];
    NSString * url = [NSString stringWithFormat:@"========異常錯誤報告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[arr componentsJoinedByString:@"\n"]];
    NSString * path = [applicationDocumentsDirectory() stringByAppendingPathComponent:@"Exception.txt"];
    // 將一個txt文件寫入沙盒
    [url writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

}


@implementation MyUncaughtExceptionHandler

// 沙盒地址
- (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

+ (void)setDefaultHandler {
    NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
}

+ (NSUncaughtExceptionHandler *)getHandler {
    return NSGetUncaughtExceptionHandler();
}

+ (void)TakeException:(NSException *)exception {
    NSArray * arr = [exception callStackSymbols];
    NSString * reason = [exception reason];
    NSString * name = [exception name];
    NSString * url = [NSString stringWithFormat:@"========異常錯誤報告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[arr componentsJoinedByString:@"\n"];

在appledelegate導入頭文件加上一個異常捕獲監(jiān)聽,用來處理程序崩潰時的回調動作 在這里也要判斷一下之前有沒有崩潰日志 如果有發(fā)送給服務器

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   #pragma mark -- 崩潰日志
    [MyUncaughtExceptionHandler setDefaultHandler];
    // 發(fā)送崩潰日志
    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 -- 發(fā)送崩潰日志
- (void)sendExceptionLogWithData:(NSData *)data path:(NSString *)path {

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 5.0f;
    //告訴AFN,支持接受 text/xml 的數據
    [AFJSONResponseSerializer serializer].acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    NSString *urlString = @"后臺地址";

    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"file" fileName:@"Exception.txt" mimeType:@"txt"];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        // 刪除文件
        NSFileManager *fileManger = [NSFileManager defaultManager];
        [fileManger removeItemAtPath:path error:nil];

    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {

    }];

測試:可以隨便建一個控制器 弄一個數組越界測試一下~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容