protobuf3 iOS 接入 protobuf
1.引入官方基础pod
谷歌将protobuf需要使用的基础类封装成了一个pod,因此可以直接安装该pod,不必再手工导入.
如下: pod "Protobuf", :git => "https://github.com/google/protobuf.git"
之所以设置git路径,是因为这样pod ‘Protobuf’, ‘~> 3.1.0’一直没有下载下来,所以直接使用了官网路径.
2.下载生成代码工具
a.安装protoc: brew install –devel protobuf 如果出现了下面的版本号,说明安装成功 ➜ ~ protoc --version libprotoc 3.0.0
关于protoc工具的使用请参考 https://developers.google.com/protocol-buffers/docs/proto3
b.另外一个方法是直接从github下载,自己编译一个protoc 链接:https://github.com/google/protobuf/tree/master/objectivec.编译完成后,
在protobuf/src下可以找到该工具
3.定义数据模型
syntax = "proto3"; package tutorial; message SearchResponse { repeated Result results = 1; } message Result { string url = 1; string title = 2; repeated string snippets = 3; }
将以上数据保存到Test.proto的文件中.
生成代码的命令为:
protoc –objc_out=tmp Test.proto
最后一个参数是定义的数据模型,生成的代码会写入objc_out对应的文件夹内.注意是两个短横杠
4.简单使用
- 直接将生成的代码拖入1创建的项目中,
- import相关头文件
- protobuf为了性能考虑,创建的都是mrc文件,因此在build phrases ->Compile
sources中给拖入的文件添加 -fno-objc-arc的标志
Result *res = [[Result alloc] init]; res.title = @"11"; NSLog(@"%@",res.description); //序列化 NSData *data = [res data]; //反序列化 NSError *error; Result *res1 = [[Result alloc] initWithData:data error:&error]; NSLog(@"%@",res1.description);
post请求:
- (void)protoPost { // 设置请求体 BidRequest * bidRequest = [[BidRequest alloc] init]; bidRequest.bid = @"bid"; bidRequest.version = @"version"; BidRequest_BidUserInfo * bidUserInfo = [[BidRequest_BidUserInfo alloc] init]; bidUserInfo.ip = @"ip"; bidRequest.bidUserInfo = bidUserInfo; BidRequest_BidAppInfo * bidAppInfo = [[BidRequest_BidAppInfo alloc] init]; bidAppInfo.appId = @"appId"; bidAppInfo.appName = @"appName"; bidRequest.bidAppInfo = bidAppInfo; BidRequest_BidAdSlotInfo * bidAdSlotInfo = [[BidRequest_BidAdSlotInfo alloc] init]; bidAdSlotInfo.slotId = @"slotId"; bidAdSlotInfo.width = 11; bidAdSlotInfo.height = 22; bidRequest.bidAdSlotInfo = bidAdSlotInfo; self.myData = [bidRequest data]; NSURL * url = [NSURL URLWithString:@"http://192.168.10.45:9988/unioncast-ssp-manager/bidding/ssp/process"]; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url]; request.timeoutInterval = 5; request.HTTPMethod = @"POST"; request.HTTPBody = self.myData; [request setValue:@"application/protobuf" forHTTPHeaderField:@"Content-Type"]; NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error) { NSLog(@"error = %@",error); return; } else { NSLog(@"------ data = %@",data); NSLog(@"success"); // 返回的数据 BidRequest * bidRequest = [BidRequest parseFromData:data error:nil]; NSLog(@"=====%@",bidRequest.description); NSString * result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",result); } }]; [task resume]; }