?Protobuf For Swift
公司項(xiàng)目重構(gòu),為了優(yōu)化網(wǎng)絡(luò)請(qǐng)求響應(yīng)的時(shí)間, 需將部份數(shù)據(jù)使用protobuf 序列化傳輸.開(kāi)始踏坑.
導(dǎo)入步聚:
1.編譯安裝.proto格式轉(zhuǎn)換器;
2.引入相應(yīng)版本的protobuf(多用CocoaPods);
3.命令行轉(zhuǎn)換成OC或swift文件并拖入項(xiàng)目中;
編譯和安裝?
先下載,進(jìn)入,列出tag,切換到對(duì)應(yīng)分支,然后build
$ git clone https://github.com/apple/swift-protobuf.git
$ cd swift-protobuf
$ swift build
command + shift + .顯示隱藏文件,進(jìn)入.build/debug文件夾下,找到protoc-gen-swift,這是一個(gè)可執(zhí)行文件,復(fù)制一份放到系統(tǒng)的PATH環(huán)境目錄下,在mac也就是磁盤(pán)/usr/local/bin下面
引入項(xiàng)目? ?pod,pod install
pod 'SwiftProtobuf'
轉(zhuǎn)換輸出
cd到Person.proto目錄,運(yùn)行下列系統(tǒng)會(huì)自動(dòng)PATH環(huán)境目錄下的protoc-gen-swift轉(zhuǎn)換,得到Person.pb.swift文件,拖入項(xiàng)目中即可
編譯命令:???protoc? (文件名) --swift_out="./"
使用:?
?? ? //從遠(yuǎn)端獲取經(jīng)過(guò)服務(wù)器序列化的data
? ? ? ? let url = URL(string: "http://192.168.1.32:10004/noauth/lottery/data?version=1")!
? ? ? ? guardletdata =try?Data.init(contentsOf: url)else{
? ? ? ? ? ? print("error")
? ? ? ? ? ? return
? ? ? ? }
? ? ? ? // 將獲取到的data轉(zhuǎn)為模型
? ? ? ? guardletmodel =try?FullData(serializedData: data)else{
?? ? ? ? ? ? print("數(shù)據(jù)反序列化失敗")
? ? ? ? ? ? return
? ? ? ? }
? ? ? ? //模型序列化為data
? ? ? ? guardletbufData =try? model.serializedData()else{
? ? ? ? ? ? print("模型序列化失敗")
? ? ? ? ? ? return
? ? ? ? }