美文网首页
iOS Swift 使用protobuff 请求简单封装

iOS Swift 使用protobuff 请求简单封装

作者: 東玖零 | 来源:发表于2019-06-13 19:07 被阅读0次

1.如何使用swiftprotobuff自行查找吧。

2.序列化和反序列号及protobuff to josn 进行打印。
A-- let data1 = try data.serializedData()
B-- let model = try messageType.init(serializedData:d)
C-- let result = try model.jsonString()

3.直接上代码吧。

static func request(path:String , method:String = "POST", data:Message, messageType:Message.Type, callback:((_ desc:RespModel)->())?) {
        do {
            let data1 = try data.serializedData()
            var request = URLRequest(url: URL(string:"http://www.xx.com" + path)!)
            request.httpMethod = method
            request.timeoutInterval = 60
            request.httpBody = data1
            let session = URLSession.shared
            let task = session.dataTask(with: request) { (data2, resp, error) in
                let res = resp?.desc() ?? RespModel()
                DLog("url = " + "http://www.xx.com" + path + " code = " + String(res.code))
                do {
                    let paras = try data.jsonString()
                    DLog("paras = " + paras)
                } catch {
                    DLog("paras to json string fail !!!")
                }
                if res.code == 200 {
                    if let d = data2 {
                        do {
                            let model = try messageType.init(serializedData:d)
                            res.result = model
                            let result = try model.jsonString()
                            DLog("result = " + result)
                        } catch {
                            res.code = 999999
                            res.error = "服务器异常,请稍候重试"
                            DLog("SwiftProtobuf 反序列化失败:",error)
                        }
                    }
                } else {
                    DLog("result = ",res.error)
                }
                if let block = callback {
                    DispatchQueue.main.async {
                        block(res)
                    }
                }
            }
            task.resume()
        } catch {
            let res = RespModel()
            res.code = 999999
            res.error = "服务器异常,请稍候重试"
            DLog("SwiftProtobuf 序列化失败:",error)
            if let block = callback {
                block(res)
            }
        }
    }

相关文章

网友评论

      本文标题:iOS Swift 使用protobuff 请求简单封装

      本文链接:https://www.haomeiwen.com/subject/zsrefctx.html