前言
最近用ProtocolBuf協(xié)議進(jìn)行網(wǎng)絡(luò)傳輸,數(shù)據(jù)也是轉(zhuǎn)為ProtocolBuf。記錄下使用流程
Protocol Buffers介紹
protocol buffer全稱Google Protocol Buffer,是Google 公司內(nèi)部的混合語言數(shù)據(jù)標(biāo)準(zhǔn)。他們用于RPC 系統(tǒng)和持續(xù)數(shù)據(jù)存儲系統(tǒng)。
Protocol Buffers是一種輕便高效的結(jié)構(gòu)化數(shù)據(jù)存儲格式,可以用于結(jié)構(gòu)化數(shù)據(jù)串行化,或者說序列化,它很適合做數(shù)據(jù)存儲或RPC 數(shù)據(jù)交換格式??捎糜谕ㄓ崊f(xié)議、數(shù)據(jù)存儲等領(lǐng)域的語言無關(guān)、平臺無關(guān)、可擴(kuò)展的序列化結(jié)構(gòu)數(shù)據(jù)格式。目前官方提供了C++、C#、DART、GO、Java、Python 六種語言的API,也可以支持其他語言,實(shí)現(xiàn)它的派生方法即可。
官方地址:https://developers.google.cn/protocol-buffers/
環(huán)境安裝
brew install automake
brew install libtool
brew install protobuf
上面安裝好protobuf完成
proto源文件轉(zhuǎn)OC
1、 終端 cd 到一個新文件架下:
touch geexLogData.proto
2、打開 編輯內(nèi)容
syntax = "proto3";
message geexLogData {
bytes body = 1;
string flagStr = 2;
}
3、生成對應(yīng)的.h 與.m文件
protoc ./geexLogData.proto --objc_out=./

使用
1、工程導(dǎo)入Protobuf
pod 'Protobuf'
2、創(chuàng)建的.h 與.m文件拖入工程;網(wǎng)上都讓加-fno-objc-arc,我沒有加也是正常
3、當(dāng)正常的model 使用
Person *person = [Person new];
person.personId = 1;
person.personName = @"Carson";
person.personGender = @"Male";
person.personMessage = @"I'm the best in the world !";
NSData *personData = [person data];
4、網(wǎng)絡(luò)傳輸
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
NSURL *url = [NSURL URLWithString: urlStr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
[request setValue:@"application/x-protobuf" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/x-protobuf" forHTTPHeaderField:@"Accept"];
request.HTTPMethod = @"POST";
geexLogBody *body = [[geexLogBody alloc] init];
body.body = parameters;
request.HTTPBody = [[body data] base64EncodedDataWithOptions:0];
AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer = responseSerializer;
[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
}] resume];
正常model賦值,講對象序列化data 然后上傳。
估計我處理的問題,我也沒發(fā)現(xiàn)比json數(shù)據(jù)少,沒感到有什么好處。 可能后臺能直接反序列化為model