高密建設(shè)局網(wǎng)站1688精品貨源網(wǎng)站入口
快速上手 iOS Protocol Buffer | 來自繽紛多彩的灰
本文主要介紹在 iOS 開發(fā)中如何快速上手使用 Protobuf。更多關(guān)于 Protobuf 的介紹和相關(guān)的功能 api,讀者可自行查閱官網(wǎng)。
Protocol Buffer(簡稱 Protobuf)是一種由Google開發(fā)的語言中立、平臺無關(guān)的序列化數(shù)據(jù)結(jié)構(gòu)的方法。它允許你定義結(jié)構(gòu)化的數(shù)據(jù),并提供一種高效且靈活的方式進(jìn)行數(shù)據(jù)序列化和反序列化。
安裝 Protobuf 工具
最簡單的方式是直接通過 brew 進(jìn)行安裝:
brew install protobuf // 支持生成.h和.m文件,和其他多種語言的文件
brew install swift-protobuf // 支持生成.swift文件
檢查是否安裝成功:
protoc --version
protoc-gen-swift --version
創(chuàng)建 .proto 文件
// 使用V3語法
syntax = "proto3"
// OC語言可選,添加模型文件前綴
option objc_class_prefix = "MY"
// message代表一個模型
message Test {
? ? string title = 1;
? ? int32 tag = 2;
? ? Request request = 3; ? ? ? ?// 自定義的 Request 類型
? ? repeated string values = 4; // 數(shù)組
}
message Request {
? ? string url = 1;
}
OC、Swift 代碼生成
Protobuf 提供api用于根據(jù).proto文件生成代碼,需傳入兩個參數(shù),生成結(jié)果與參數(shù)的傳入順序無關(guān):
- .proto 文件的路徑(下文中用 source_path 表示)
- 需要生成的目標(biāo)語言(下文用 target_language 表示)以及文件的輸出路徑(下文用 target_path 表示)
protoc source_path/xxx.proto --target_language_out=target_path
?protoc --objc_out=. xxx.proto ? ? ?// 在當(dāng)前文件夾根據(jù)xxx.proto生成.h和.m文件
protoc xxx.proto --swift_out=. ? ? // 在當(dāng)前文件夾根據(jù)xxx.proto生成.swift文件
在 iOS 工程中的使用
1.工程添加依賴
pod 'Protobuf' ? ? ? ? ?// OC和其他多種語言的能力依賴
pod 'SwiftProtobuf' ? ? // swift能力依賴
2.把轉(zhuǎn)換后的代碼文件加入到工程。
3.跟正常使用某個類的方法一樣。
/*{"title": "test","tag": 1,"request": {"url": "www.fivehow.com"},"values": ["value1", "value2"]}*/let request = Request.with { $0.url = "www.whlcj.github.io" }
// ProtoBuf data
let test = Test.with {$0.title = "test"$0.tag = 1$0.request = request$0.values = ["value1", "value2"]
}
let binaryData = try? test.serializedData()
guard let binaryData = binaryData else { return }
_ = try? Test(serializedData: binaryData)
// Json Data
let jsonStr = "{\"title\":\"test\", \"tag\":1, \"request\":{\"url\":\"www.whlcj.github.io\"},\"values\":[\"value1\", \"value2\"]}"let jsonStrData = jsonStr.data(using: .utf8)// 對比 data length
print("binaryData: \(binaryData.count)") // 43guard let jsonStrData = jsonStrData else { return }
print("jsonStrData: \(jsonStrData.count)") // 92
protobuf 基礎(chǔ)類型與Swift類型映射關(guān)系
Proto type | Swift Type |
---|---|
int32 | Int32 |
sint32 | Int32 |
sfixed32 | Int32 |
uint32 | UInt32 |
fixed32 | UInt32 |
int64 | Int64 |
sint64 | Int64 |
sfixed64 | Int64 |
uint64 | UInt64 |
fixed64 | UInt64 |
bool | Bool |
float | Float |
double | Double |
string | String |
bytes | Data |