谷歌將protobuf須要使用的基礎類封裝成了一個pod,所以能夠直接安裝該pod,沒必要再手工導入.
以下: pod "Protobuf", :git => "https://github.com/google/protobuf.git"
之因此設置git路徑,是由於這樣pod ‘Protobuf’, ‘~> 3.1.0’一直沒有下載下來,因此直接使用了官網路徑.git
a.安裝protoc: brew install –devel protobuf 若是出現了下面的版本號,說明安裝成功 ➜ ~ protoc --version libprotoc 3.0.0
關於protoc工具的使用請參考 https://developers.google.com/protocol-buffers/docs/proto3github
b.另一個方法是直接從github下載,本身編譯一個protoc 連接:https://github.com/google/protobuf/tree/master/objectivec.編譯完成後,
在protobuf/src下能夠找到該工具session
syntax = "proto3"; package tutorial; message SearchResponse { repeated Result results = 1; } message Result { string url = 1; string title = 2; repeated string snippets = 3; }
將以上數據保存到Test.proto的文件中.app
生成代碼的命令爲:
protoc –objc_out=tmp Test.proto
最後一個參數是定義的數據模型,生成的代碼會寫入objc_out對應的文件夾內.注意是兩個短橫槓工具
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請求: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]; }