為了更好的維護iosAPP,處理程序崩潰是必需要做的,那么如何收集用戶使用時出現的崩潰呢,基本的方法如下:
1.上傳appStore的app,可以通過iTunes Stroe獲取
2.利用Xcode獲取。
3. Crashlytics,Hockeyapp ,友盟,Bugly 等等。
4.通過iOS SDK中提供了一個現成的函數 NSSetUncaughtExceptionHandler 用來做異常處理
利用NSSetUncaughtExceptionHandler,當程序異常退出的時候,可以先進行處理,然后做一些自定義的動作,並通知開發者,是大多數軟件都選擇的方法。下面就介紹如何在iOS中實現:
第一步:創建崩潰獲取類crash
.h文件
@interface Crash : NSObject
//// 崩潰時的回調函數
void uncaughtExceptionHandler(NSException *exception);
@end
.m文件:
#import "Crash.h"
@implementation Crash
void uncaughtExceptionHandler(NSException *exception){
NSArray *stackArry= [exception callStackSymbols];
NSString *reason = [exception reason];
NSString *name = [exception name];
NSString *exceptionInfo = [NSString stringWithFormat:@"Exception name:%@\nException reatoin:%@\nException stack :%@",name,reason,stackArry];
NSLog(@"%@",exceptionInfo);
//保存到本地沙盒中
[exceptionInfo writeToFile:[NSString stringWithFormat:@"%@/Documents/eror.log",NSHomeDirectory()] atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
@end
第二步在Appdelegate中注冊消息方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
//注冊消息處理函數的處理方法
NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
// 發送崩潰日志
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];
}
}
第三步:崩潰日志發動到服務器
#pragma mark -- 發送崩潰日志
- (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) {
}];
}