swift崩溃日志收集与上传

在做崩溃日志收集与上传的时候用OC写了一个demo可以正常工作(OC版本的资料网上很多,这里不赘述),于是想采用现成的demo进行OC与Swift将模块集成到Swift项目,不过集成完毕后不管如何程序始终不会走异常监听的回调,因此无法将崩溃信息保存到本地,后来在同事推荐的一篇文章中找到了用Swift写的崩溃日志收集demo,文章链接:http://www.th7.cn/Program/IOS/201701/1086561.shtml ,看完后深受启发,将代码封装了一下,在需要使用的时候直接将下面的代码复制,在上传方法中添加服务器地址并导入第三方库AFNetworking即可使用:

import UIKit
import AFNetworking

class TBUncaughtExceptionHandler: NSObject {
    
    static let shared = TBUncaughtExceptionHandler()
    
    fileprivate override init() {
    }
    
    public func exceptionLogWithData() {
        setDefaultHandler()
        let path = getdataPath()
//        print(path)
        let data = NSData.init(contentsOfFile: path)
        if data != nil {
            //            let crushStr = String.init(data: data! as Data, encoding: String.Encoding.utf8)
            //            print(crushStr!)
            //上传数据
            sendExceptionLogWithData(data: data! as Data, path: path)
            
        }
        
        //测试数据
//        let arry:NSArray = ["1"]
//        print("%@",arry[5])
        
    }
    
    ///沙盒路径
    fileprivate func getdataPath() -> String{
        let str = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
        let urlPath = str.appending("/Exception.txt")
        return urlPath
    }
    
    ///异常回调
    fileprivate func setDefaultHandler() {
        NSSetUncaughtExceptionHandler { (exception) in
            let arr:NSArray = exception.callStackSymbols as NSArray
            let reason:String = exception.reason!
            let name:String = exception.name.rawValue
            let date:NSDate = NSDate()
            let timeFormatter = DateFormatter()
            timeFormatter.dateFormat = "YYYY/MM/dd hh:mm:ss SS"
            let strNowTime = timeFormatter.string(from: date as Date) as String
            let url:String = String.init(format: "========异常错误报告========\ntime:%@\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",strNowTime,name,reason,arr.componentsJoined(by: "\n"))
            let documentpath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
            let path = documentpath.appending("/Exception.txt")
            do{
                try
                    url.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
            }catch{}
        }
    }
    
    ///上传
    fileprivate func sendExceptionLogWithData(data:Data,path:String){
        let manager = AFHTTPSessionManager()
        manager.requestSerializer.timeoutInterval = 5.0
        AFJSONResponseSerializer().acceptableContentTypes = NSSet(object: "text/plain") as? Set
        manager.post("服务器地址", parameters: nil, constructingBodyWith: { (formData) in
            formData.appendPart(withFileData: data, name: "file", fileName: "Exception.txt", mimeType: "txt")
        }, progress: nil, success: { (task, responseObject) in
            let fileManger = FileManager.default
            do {
                try fileManger.removeItem(atPath: path)
            }catch{
                
            }
        }) { (task, error) in
            //上传失败
            print(error)
        }
    }
}

使用方法:在AppDelegate中

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        TBUncaughtExceptionHandler.shared.exceptionLogWithData()
        
        return true
    }

你可能感兴趣的:(swift崩溃日志收集与上传)