2020-06-18

?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

? ? ? ? }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容