客户也不知道怎么了,突然要我自己收集app的crash信息,然后发送到他的服务器,我就蛋疼了,毕竟crash的原因千千万,自己写难免很蛋疼,上网搜了很多资料,千篇一律唉,大同小异唉,都是OC的,大致代码是下面这种:
自己先手动创建一个类,姑且叫做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];// 崩溃的原因 可以有崩溃的原因(数组越界,字典nil,调用未知方法...) 崩溃的控制器以及方法
NSString *name = [exception name];
NSString *crashText = [NSString stringWithFormat:@"=============异常崩溃报告=============\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,数组越界
NSArray *arr = [NSArray arrayWithObjects:@0,@1, nil];
NSLog(@"arr2=%@)",arr[2]);
return YES;
}
接着我们运行后,打印出来就可以看到crash信息了
然而,我给客户开发用的语言是swift2.2,有点蛋疼,因为我一直测试不出来收集的crash信息,我是这样写的:
我写了一个类UncaughtExceptionHandlerHelper:
import UIKit
class UncaughtExceptionHandlerHelper: NSObject {
class func UncaughtExceptionHandler(exception:NSException){
let name = exception.name
// 崩溃的原因 可以有崩溃的原因(数组越界,字典nil,调用未知方法...) 崩溃的控制器以及方法
let reason = exception.reason
//详情
let arr = exception.callStackSymbols as NSArray
//当前app版本
let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as? String
//当前设备
let deviceModel = UIDevice.currentDevice().model
//系统版本
let sysVersion = UIDevice.currentDevice().systemVersion
//崩溃报告的格式,可以自己重新写
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
}
然而运行没有什么卵用,一直没有去到回调,然后我一度以为是swift无法支持这两个东西,搜集了很多资料,看到和自己的问题相似的也就几个网址,说真的网上swift这方面的还真少,主要有用的是这个网址:(大家有空也可以多探讨一下)
https://stackoverflow.com/questions/25441302/how-should-i-use-nssetuncaughtexceptionhandler-in-swift
最后经过朋友的指点,终于明白了问题在于我所做的模拟crash-模拟crash应该修改为:
let arr = NSArray(array: [0,1])
print("arr2=\(arr[2])")
然后运行,成功进入:
至于原因照朋友说的应该是NSSetUncaughtExceptionHandler只支持OC的类,不支持Swift的如Array,故而改过去就可以收集到了。
其实这么看来,这个NSSetUncaughtExceptionHandler并不能捕捉到所有的Crash,大概只能捕获到NSException类的。
回到正题,收集到crash信息之后,最好是保存到本地下次启动app的时候再发送,不建议立即发送到服务器,然后发送的位置也是看自己需求而定,一般是在didFinishLaunchingWithOptions最后发送,然后我写得是这样的:
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last
let dataPath = path! + "/Exception.txt"
let data = NSData(contentsOfFile: dataPath)
if data != nil{
//这个ApiHelper是我自己封装的请求类,不要在意这些细节
ApiHelper.sharedInstance.sendException(data!, successBack: {
if NSFileManager.defaultManager().fileExistsAtPath(dataPath) == true{
do{
try NSFileManager.defaultManager().removeItemAtPath(dataPath)
}catch{
print(error)
}
}
})
}
看服务器是要data数据还是字符串数据,转为字符串也很简单:
let exceptionText = String(data: data!, encoding: NSUTF8StringEncoding)
这样子基本就OK了,如果有什么问题,欢迎各位指出来,在此谢谢了