ProtocolBuffer是谷歌发明的一种数据传输协议
关于ProtocolBuffer的更多介绍请看这里
ProtocolBuffer的环境配置及安装
-
环境安装
打开终端依次之行如下命令
brew install automake
brew install libtool
brew install protobuf
-
客户端集成(通过cocoapods)
use_frameworks!
pod 'ProtocolBuffers-Swift'
-
服务器集成
因为服务器不能直接使用cocoapods集成,需要将工程编译为静态库来集成
1.到Git中下载整个库
2.执行脚本: ./scripts/build.sh
3.添加: ./src/ProtocolBuffers/ProtocolBuffers.xcodeproj到项目中
ProtocolBuffer的使用
-
创建.proto文件
1.在项目中, 创建一个(或多个).proto文件
2.之后会通过该文件, 自动帮我们生成需要的源文件(比如C++生成.cpp源文件, 比如java生成.java源文件, Swift就生成.swift源文件) -
源码规范
syntax = "proto2";
message Person {
required int64 id = 1;
required string name = 2;
optional string email = 3;
}
规范说明
1.syntax = "proto2"; 为定义使用的版本号, 目前常用版本proto2/proto3
2.message是消息定义的关键字,等同于C++/Swift中的struct/class,或是Java中的class
3.Person为消息的名字,等同于结构体名或类名
4.required前缀表示该字段为必要字段,既在序列化和反序列化之前该字段必须已经被赋值
5.optional前缀表示该字段为可选字段, 既在序列化和反序列化时可以没有被赋值
6.repeated通常被用在数组字段中
7.int64和string分别表示整型和字符串型的消息字段
8.id和name和email分别表示消息字段名,等同于Swift或是C++中的成员变量名
9.标签数字1和2则表示不同的字段在序列化后的二进制数据中的布局位置, 需要注意的是该值在同一message中不能重复
定义有枚举类型Protocol Buffer消息
enum UserStatus {
OFFLINE = 0; //表示处于离线状态的用户
ONLINE = 1; //表示处于在线状态的用户
}
message UserInfo {
required int64 acctID = 1;
required string name = 2;
required UserStatus status = 3;
}
定义有类型嵌套
enum UserStatus {
OFFLINE = 0;
ONLINE = 1;
}
message UserInfo {
required int64 acctID = 1;
required string name = 2;
required UserStatus status = 3;
}
message LogonRespMessage {
required LoginResult logonResult = 1;
required UserInfo userInfo = 2;
}
-
代码编写完成后, 生成对应语言代码
protoc person.proto --swift_out="./"
环境配置遇到的问题
-
错误1
执行下面命令后
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
报错误如下图:
![](https://img.haomeiwen.com/i2634897/7346db8b2ee09de0.png)
解决方法如上图箭头所示,删除Deleting /Library/Caches/目录下的Homebrew缓存数据
-
可能错误2
作者当时运行第二个命令时报如下错误
![](https://img.haomeiwen.com/i2634897/f537509d1f8506dc.png)
说目录已存在让删除目录:so,就删除目录并执行
brew update
如下图![](https://img.haomeiwen.com/i2634897/1fa04b1fa7636913.png)
-
可能错误3
Error: The current working directory doesn't exist, cannot proceed.
shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
由于作者当时错误一处理失败导致执行brew update
出现此错误
请看图2的第二个箭头
-
可能错误4
同样是由于作者当时处理问题1出现失误造成
< Error: Fetching /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core failed!
原因:是由于该文件夹找不到
解决方法: cd 到上一层目录执行命令就行了
-
可能错误5
执行brew install protobuf
遇见此错误
<Error: You must brew link autoconf automake libtool
before protobuf can be installed
如图
![](https://img.haomeiwen.com/i2634897/fb93cd6c1135558c.png)
解决办法:其实终端有提示,没错执行这个
brew link autoconf automake libtool
网友评论