客戶也不知道怎么了真友,突然要我自己收集app的crash信息黄痪,然后發(fā)送到他的服務(wù)器,我就蛋疼了盔然,畢竟crash的原因千千萬桅打,自己寫難免很蛋疼是嗜,上網(wǎng)搜了很多資料,千篇一律唉挺尾,大同小異唉鹅搪,都是OC的,大致代碼是下面這種:
自己先手動(dòng)創(chuàng)建一個(gè)類遭铺,姑且叫做CrashCaughtHelper丽柿;
然后.h文件是這樣的:
#import <Foundation/Foundation.h>
@interface CrashCaughtHelper : NSObject
+ (void)setDefaultHandler;
+ (NSUncaughtExceptionHandler*)getHandler;
@end
接著.m文件是這樣的:
#import "CrashCaughtHelper.h"
void UncaughtExceptionHandler(NSException *exception) {
NSArray *arr = [exception callStackSymbols];
NSString *reason = [exception reason];// 崩潰的原因 可以有崩潰的原因(數(shù)組越界,字典nil,調(diào)用未知方法...) 崩潰的控制器以及方法
NSString *name = [exception name];
NSString *crashText = [NSString stringWithFormat:@"=============異常崩潰報(bào)告=============\nname:\n%@\nreason:\n%@\ncallStackSymbols:\n%@",
name,reason,[arr componentsJoinedByString:@"\n"]];
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Exception.txt"];
[crashText writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
@implementation CrashCaughtHelper
-(NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
+ (void)setDefaultHandler
{
NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);
}
+ (NSUncaughtExceptionHandler*)getHandler
{
return NSGetUncaughtExceptionHandler();
}
@end
然后在AppDelegate.m中的didFinishLaunchingWithOptions要這么寫:
#import "AppDelegate.h"
#import "CrashCaughtHelper.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[CrashCaughtHelper setDefaultHandler];
//下面是模擬crash,數(shù)組越界
NSArray *arr = [NSArray arrayWithObjects:@0,@1, nil];
NSLog(@"arr2=%@)",arr[2]);
return YES;
}
接著我們運(yùn)行后魂挂,打印出來就可以看到crash信息了
然而甫题,我給客戶開發(fā)用的語言是swift2.2,有點(diǎn)蛋疼涂召,因?yàn)槲乙恢睖y(cè)試不出來收集的crash信息坠非,我是這樣寫的:
我寫了一個(gè)類UncaughtExceptionHandlerHelper:
import UIKit
class UncaughtExceptionHandlerHelper: NSObject {
class func UncaughtExceptionHandler(exception:NSException){
let name = exception.name
// 崩潰的原因 可以有崩潰的原因(數(shù)組越界,字典nil,調(diào)用未知方法...) 崩潰的控制器以及方法
let reason = exception.reason
//詳情
let arr = exception.callStackSymbols as NSArray
//當(dāng)前app版本
let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as? String
//當(dāng)前設(shè)備
let deviceModel = UIDevice.currentDevice().model
//系統(tǒng)版本
let sysVersion = UIDevice.currentDevice().systemVersion
//崩潰報(bào)告的格式,可以自己重新寫
let crashText = "App Version:\(currentVersion!)\nVersion:\(sysVersion)\nVerdor:\(deviceModel)\nname:\(name)\nreason:\n\(reason)\ncallStackSymbols:\n\(arr.componentsJoinedByString("\n"))"
//保存路徑
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! + "/Exception.txt"
// 將txt文件寫入沙盒
do{
try crashText.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding)
}catch{
print(error)
}
}
class func setDefaultHandler(){
NSSetUncaughtExceptionHandler { (exception) in
UncaughtExceptionHandlerHelper.UncaughtExceptionHandler(exception)
}
}
class func getHandler()->NSUncaughtExceptionHandler{
return NSGetUncaughtExceptionHandler()!
}
}
然后AppDelegate中我是這么寫得:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UIAlertViewDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UncaughtExceptionHandlerHelper.setDefaultHandler()
//模擬crash
let arr = [0,1]
print("arr2=\(arr[2])")
return true
}
然而運(yùn)行沒有什么卵用果正,一直沒有去到回調(diào)麻顶,然后我一度以為是swift無法支持這兩個(gè)東西,搜集了很多資料舱卡,看到和自己的問題相似的也就幾個(gè)網(wǎng)址辅肾,說真的網(wǎng)上swift這方面的還真少,主要有用的是這個(gè)網(wǎng)址:(大家有空也可以多探討一下)
https://stackoverflow.com/questions/25441302/how-should-i-use-nssetuncaughtexceptionhandler-in-swift
最后經(jīng)過朋友的指點(diǎn)轮锥,終于明白了問題在于我所做的模擬crash-模擬crash應(yīng)該修改為:
let arr = NSArray(array: [0,1])
print("arr2=\(arr[2])")
然后運(yùn)行矫钓,成功進(jìn)入:
至于原因照朋友說的應(yīng)該是NSSetUncaughtExceptionHandler只支持OC的類,不支持Swift的如Array舍杜,故而改過去就可以收集到了新娜。
其實(shí)這么看來,這個(gè)NSSetUncaughtExceptionHandler并不能捕捉到所有的Crash既绩,大概只能捕獲到NSException類的概龄。
回到正題,收集到crash信息之后饲握,最好是保存到本地下次啟動(dòng)app的時(shí)候再發(fā)送私杜,不建議立即發(fā)送到服務(wù)器,然后發(fā)送的位置也是看自己需求而定救欧,一般是在didFinishLaunchingWithOptions最后發(fā)送衰粹,然后我寫得是這樣的:
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last
let dataPath = path! + "/Exception.txt"
let data = NSData(contentsOfFile: dataPath)
if data != nil{
//這個(gè)ApiHelper是我自己封裝的請(qǐng)求類,不要在意這些細(xì)節(jié)
ApiHelper.sharedInstance.sendException(data!, successBack: {
if NSFileManager.defaultManager().fileExistsAtPath(dataPath) == true{
do{
try NSFileManager.defaultManager().removeItemAtPath(dataPath)
}catch{
print(error)
}
}
})
}
看服務(wù)器是要data數(shù)據(jù)還是字符串?dāng)?shù)據(jù)笆怠,轉(zhuǎn)為字符串也很簡(jiǎn)單:
let exceptionText = String(data: data!, encoding: NSUTF8StringEncoding)
這樣子基本就OK了铝耻,如果有什么問題,歡迎各位指出來蹬刷,在此謝謝了