对后台了解不多,但是最近在接触Protobuf,学到不少东西,所以就此分享出来,和广大iOS developers交流下。
首先了解下Protobuf
用专业的话来说
Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准,是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。它很适合做数据存储或 RPC 数据交换格式。可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。目前提供了 C++、Java、Python 三种语言的 API。
用我的理解就是
因为我们公司后台使用的是Python,使用Protobuf主要是因为以下三点:
数据结构可以自定义,以便各个开发平台的数据转换
消息载体相比XML要轻便灵活,提高解析性能
需要得到自定义的proto文件才能进行反序列化,否则难以解析数据,很好地加强了数据保密性
安装Protobuf编译器
基于Protobuf良好的特性,那么我们可以着手来体验一下
首先在MAC上部署安装环境
用terminal进行部署,
在terminal输入brew -v检查MAC是否装有brew,没有的话就安装brew,输入以下命令
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)”
如果这句命令fail,可以直接进brew的官网,copy Homebrew的官网提供的命令
继续部署
brew install automake
为了方便操作对比,将terminal的输出结果也展示出来好做对比
==>Installing dependencies for automake:autoconf
==>Installing automake dependency:autoconf
==>Downloading https://homebrew.bintray.com/bottles/autoconf-2.69.el_capitan.bo
######################################################################## 100.0%
==>Pouring autoconf-2.69.el_capitan.bottle.4.tar.gz
==>Caveats
Emacs Lisp files have been installed to:
/usr/local/share/emacs/site-lisp/autoconf
==>Summary
:beer: /usr/local/Cellar/autoconf/2.69: 70 files, 3.1M
==>Installingautomake
==>Downloading https://homebrew.bintray.com/bottles/automake-1.15.el_capitan.bo
######################################################################## 100.0%
==>Pouring automake-1.15.el_capitan.bottle.2.tar.gz
:beer: /usr/local/Cellar/automake/1.15: 130 files, 3.2M
brew install libtool
==>Downloading https://homebrew.bintray.com/bottles/libtool-2.4.6.el_capitan.bo
######################################################################## 100.0%
==>Pouring libtool-2.4.6.el_capitan.bottle.tar.gz
==>Caveats
In order to prevent conflicts with Apple's own libtool we have prepended a "g"
so, you have instead: glibtool and glibtoolize.
==>Summary
:beer: /usr/local/Cellar/libtool/2.4.6: 69 files, 3.8M
brew install protobuf
==> Downloading https://homebrew.bintray.com/bottles/protobuf-2.6.1.el_capitan.b
######################################################################## 100.0%
==> Pouring protobuf-2.6.1.el_capitan.bottle.3.tar.gz
==> Caveats
Editor support and examples have been installed to:
/usr/local/Cellar/protobuf/2.6.1/share/doc/protobuf
Python modules have been installed and Homebrew's site-packages is not
in your Python sys.path, so you will not be able to import the modules
this formula installed. If you plan to develop with these modules,
please run:
mkdir -p /Users/huhuimin/Library/Python/2.7/lib/python/site-packages
echo 'import site; site.addsitedir("/usr/local/lib/python2.7/site-packages")' >> /Users/huhuimin/Library/Python/2.7/lib/python/site-packages/homebrew.pth
==> Summary
:beer: /usr/local/Cellar/protobuf/2.6.1: 118 files, 7.1M
安装Protobuf的编译器
继续输入命令
git clone https://github.com/alexeyxo/protobuf-objc.git
以下是terminal输出结果
Cloning into 'protobuf-objc'...
remote: Counting objects: 2788, done.
remote: Total 2788 (delta 0), reused 0 (delta 0), pack-reused 2788
Receiving objects: 100% (2788/2788), 32.92 MiB | 316.00 KiB/s, done.
Resolving deltas: 100% (1761/1761), done.
Checking connectivity... done.
cd ~/protobuf-objc
./autogen.sh
glibtoolize: putting auxiliary files in '.'.
glibtoolize: copying file './ltmain.sh'
glibtoolize: putting macros in AC_CONFIG_MACRO_DIRS, 'm4'.
glibtoolize: copying file 'm4/libtool.m4'
glibtoolize: copying file 'm4/ltoptions.m4'
glibtoolize: copying file 'm4/ltsugar.m4'
glibtoolize: copying file 'm4/ltversion.m4'
glibtoolize: copying file 'm4/lt~obsolete.m4'
configure.ac:13: installing './compile'
configure.ac:9: installing './config.guess'
configure.ac:9: installing './config.sub'
configure.ac:10: installing './install-sh'
configure.ac:10: installing './missing'
src/compiler/Makefile.am:5: warning: source file 'google/protobuf/objectivec-descriptor.pb.cc' is in a subdirectory,
src/compiler/Makefile.am:5: but option 'subdir-objects' is disabled
automake: warning: possible forward-incompatibility.
automake: At least a source file is in a subdirectory, but the 'subdir-objects'
automake: automake option hasn't been enabled. For now, the corresponding output
automake: object file(s) will be placed in the top-level directory. However,
automake: this behaviour will change in future Automake versions: they will
automake: unconditionally cause object files to be placed in the same subdirectory
automake: of the corresponding sources.
automake: You are advised to start using 'subdir-objects' option throughout your
automake: project, to avoid future incompatibilities.
src/compiler/Makefile.am: installing './depcomp'
./configure
checking build system type... x86_64-apple-darwin15.0.0
checking host system type... x86_64-apple-darwin15.0.0
checking target system type... x86_64-apple-darwin15.0.0
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... ./install-sh -c -d
checking for gawk... no
checking for mawk... no
checking for nawk... no
checking for awk... awk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking whether gcc understands -c and -o together... yes
checking for style of include used by make... GNU
checking dependency style of gcc... gcc3
checking for g++... g++
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking dependency style of g++... gcc3
checking C++ compiler flags...... use default: -g -O2 -DNDEBUG
checking how to print strings... printf
checking for a sed that does not truncate output... /usr/bin/sed
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for fgrep... /usr/bin/grep -F
checking for ld used by gcc... /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld
checking if the linker (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld) is GNU ld... no
checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm
checking the name lister (/usr/bin/nm) interface... BSD nm
checking whether ln -s works... yes
checking the maximum length of command line arguments... 196608
checking how to convert x86_64-apple-darwin15.0.0 file names to x86_64-apple-darwin15.0.0 format... func_convert_file_noop
checking how to convert x86_64-apple-darwin15.0.0 file names to toolchain format... func_convert_file_noop
checking for /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld option to reload object files... -r
checking for objdump... no
checking how to recognize dependent libraries... pass_all
checking for dlltool... no
checking how to associate runtime and link libraries... printf %s\n
checking for ar... ar
checking for archiver @FILE support... no
checking for strip... strip
checking for ranlib... ranlib
checking command to parse /usr/bin/nm output from gcc object... ok
checking for sysroot... no
checking for a working dd... /bin/dd
checking how to truncate binary pipes... /bin/dd bs=4096 count=1
checking for mt... no
checking if : is a manifest tool... no
checking for dsymutil... dsymutil
checking for nmedit... nmedit
checking for lipo... lipo
checking for otool... otool
checking for otool64... no
checking for -single_module linker flag... yes
checking for -exported_symbols_list linker flag... yes
checking for -force_load linker flag... yes
checking how to run the C preprocessor... gcc -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking for dlfcn.h... yes
checking for objdir... .libs
checking if gcc supports -fno-rtti -fno-exceptions... yes
checking for gcc option to produce PIC... -fno-common -DPIC
checking if gcc PIC flag -fno-common -DPIC works... yes
checking if gcc static flag -static works... no
checking if gcc supports -c -o file.o... yes
checking if gcc supports -c -o file.o... (cached) yes
checking whether the gcc linker (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld) supports shared libraries... yes
checking dynamic linker characteristics... darwin15.0.0 dyld
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... yes
checking whether to build static libraries... yes
checking how to run the C++ preprocessor... g++ -E
checking for ld used by g++... /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld
checking if the linker (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld) is GNU ld... no
checking whether the g++ linker (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld) supports shared libraries... yes
checking for g++ option to produce PIC... -fno-common -DPIC
checking if g++ PIC flag -fno-common -DPIC works... yes
checking if g++ static flag -static works... no
checking if g++ supports -c -o file.o... yes
checking if g++ supports -c -o file.o... (cached) yes
checking whether the g++ linker (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld) supports shared libraries... yes
checking dynamic linker characteristics... darwin15.0.0 dyld
checking how to hardcode library paths into programs... immediate
checking for ANSI C header files... (cached) yes
checking fcntl.h usability... yes
checking fcntl.h presence... yes
checking for fcntl.h... yes
checking for inttypes.h... (cached) yes
checking limits.h usability... yes
checking limits.h presence... yes
checking for limits.h... yes
checking for stdlib.h... (cached) yes
checking for unistd.h... (cached) yes
checking for working memcmp... yes
checking for working strtod... yes
checking for ftruncate... yes
checking for memset... yes
checking for mkdir... yes
checking for strchr... yes
checking for strerror... yes
checking for strtol... yes
checking google/protobuf/stubs/common.h usability... no
checking google/protobuf/stubs/common.h presence... no
checking for google/protobuf/stubs/common.h... no
configure: error:
ERROR: protobuf headers are required.
You must either install protobuf from google,
or if you have it installed in a custom location
you must add '-Iincludedir' to CXXFLAGS
and '-Llibdir' to LDFLAGS.
If you did not specify a prefix when installing
protobuf, try
'./configure CXXFLAGS=-I/usr/local/include LDFLAGS=-L/usr/local/lib'
In some 64-bit environments, try LDFLAGS=-L/usr/local/lib64.
按照terminal的提示继续输入命令
./configure CXXFLAGS=-I/usr/local/include LDFLAGS=-L/usr/local/lib
checking build system type... x86_64-apple-darwin15.0.0
checking host system type... x86_64-apple-darwin15.0.0
checking target system type... x86_64-apple-darwin15.0.0
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... ./install-sh -c -d
checking for gawk... no
checking for mawk... no
checking for nawk... no
checking for awk... awk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking whether gcc understands -c and -o together... yes
checking for style of include used by make... GNU
checking dependency style of gcc... gcc3
checking for g++... g++
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking dependency style of g++... gcc3
checking C++ compiler flags...... use user-supplied: -I/usr/local/include
checking how to print strings... printf
checking for a sed that does not truncate output... /usr/bin/sed
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for fgrep... /usr/bin/grep -F
checking for ld used by gcc... /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld
checking if the linker (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld) is GNU ld... no
checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm
checking the name lister (/usr/bin/nm) interface... BSD nm
checking whether ln -s works... yes
checking the maximum length of command line arguments... 196608
checking how to convert x86_64-apple-darwin15.0.0 file names to x86_64-apple-darwin15.0.0 format... func_convert_file_noop
checking how to convert x86_64-apple-darwin15.0.0 file names to toolchain format... func_convert_file_noop
checking for /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld option to reload object files... -r
checking for objdump... no
checking how to recognize dependent libraries... pass_all
checking for dlltool... no
checking how to associate runtime and link libraries... printf %s\n
checking for ar... ar
checking for archiver @FILE support... no
checking for strip... strip
checking for ranlib... ranlib
checking command to parse /usr/bin/nm output from gcc object... ok
checking for sysroot... no
checking for a working dd... /bin/dd
checking how to truncate binary pipes... /bin/dd bs=4096 count=1
checking for mt... no
checking if : is a manifest tool... no
checking for dsymutil... dsymutil
checking for nmedit... nmedit
checking for lipo... lipo
checking for otool... otool
checking for otool64... no
checking for -single_module linker flag... yes
checking for -exported_symbols_list linker flag... yes
checking for -force_load linker flag... yes
checking how to run the C preprocessor... gcc -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking for dlfcn.h... yes
checking for objdir... .libs
checking if gcc supports -fno-rtti -fno-exceptions... yes
checking for gcc option to produce PIC... -fno-common -DPIC
checking if gcc PIC flag -fno-common -DPIC works... yes
checking if gcc static flag -static works... no
checking if gcc supports -c -o file.o... yes
checking if gcc supports -c -o file.o... (cached) yes
checking whether the gcc linker (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld) supports shared libraries... yes
checking dynamic linker characteristics... darwin15.0.0 dyld
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... yes
checking whether to build static libraries... yes
checking how to run the C++ preprocessor... g++ -E
checking for ld used by g++... /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld
checking if the linker (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld) is GNU ld... no
checking whether the g++ linker (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld) supports shared libraries... yes
checking for g++ option to produce PIC... -fno-common -DPIC
checking if g++ PIC flag -fno-common -DPIC works... yes
checking if g++ static flag -static works... no
checking if g++ supports -c -o file.o... yes
checking if g++ supports -c -o file.o... (cached) yes
checking whether the g++ linker (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld) supports shared libraries... yes
checking dynamic linker characteristics... darwin15.0.0 dyld
checking how to hardcode library paths into programs... immediate
checking for ANSI C header files... (cached) yes
checking fcntl.h usability... yes
checking fcntl.h presence... yes
checking for fcntl.h... yes
checking for inttypes.h... (cached) yes
checking limits.h usability... yes
checking limits.h presence... yes
checking for limits.h... yes
checking for stdlib.h... (cached) yes
checking for unistd.h... (cached) yes
checking for working memcmp... yes
checking for working strtod... yes
checking for ftruncate... yes
checking for memset... yes
checking for mkdir... yes
checking for strchr... yes
checking for strerror... yes
checking for strtol... yes
checking google/protobuf/stubs/common.h usability... yes
checking google/protobuf/stubs/common.h presence... no
configure: WARNING: google/protobuf/stubs/common.h: accepted by the compiler, rejected by the preprocessor!
configure: WARNING: google/protobuf/stubs/common.h: proceeding with the compiler's result
checking for google/protobuf/stubs/common.h... yes
checking that generated files are newer than configure... done
configure: creating ./config.status
config.status: creating Makefile
config.status: creating src/compiler/Makefile
config.status: creating config.h
config.status: executing depfiles commands
config.status: executing libtool commands
make
/Applications/Xcode.app/Contents/Developer/usr/bin/make all-recursive
Making all in src/compiler
g++ -DHAVE_CONFIG_H -I. -I../.. -I/usr/local/include -MT main.o -MD -MP -MF .deps/main.Tpo -c -o main.o main.cc
mv -f .deps/main.Tpo .deps/main.Po
g++ -DHAVE_CONFIG_H -I. -I../.. -I/usr/local/include -MT objc_enum_field.o -MD -MP -MF .deps/objc_enum_field.Tpo -c -o objc_enum_field.o objc_enum_field.cc
mv -f .deps/objc_enum_field.Tpo .deps/objc_enum_field.Po
g++ -DHAVE_CONFIG_H -I. -I../.. -I/usr/local/include -MT objc_file.o -MD -MP -MF .deps/objc_file.Tpo -c -o objc_file.o objc_file.cc
mv -f .deps/objc_file.Tpo .deps/objc_file.Po
g++ -DHAVE_CONFIG_H -I. -I../.. -I/usr/local/include -MT objc_message_field.o -MD -MP -MF .deps/objc_message_field.Tpo -c -o objc_message_field.o objc_message_field.cc
mv -f .deps/objc_message_field.Tpo .deps/objc_message_field.Po
g++ -DHAVE_CONFIG_H -I. -I../.. -I/usr/local/include -MT objc_enum.o -MD -MP -MF .deps/objc_enum.Tpo -c -o objc_enum.o objc_enum.cc
mv -f .deps/objc_enum.Tpo .deps/objc_enum.Po
g++ -DHAVE_CONFIG_H -I. -I../.. -I/usr/local/include -MT objc_generator.o -MD -MP -MF .deps/objc_generator.Tpo -c -o objc_generator.o objc_generator.cc
mv -f .deps/objc_generator.Tpo .deps/objc_generator.Po
g++ -DHAVE_CONFIG_H -I. -I../.. -I/usr/local/include -MT objc_primitive_field.o -MD -MP -MF .deps/objc_primitive_field.Tpo -c -o objc_primitive_field.o objc_primitive_field.cc
mv -f .deps/objc_primitive_field.Tpo .deps/objc_primitive_field.Po
g++ -DHAVE_CONFIG_H -I. -I../.. -I/usr/local/include -MT objc_extension.o -MD -MP -MF .deps/objc_extension.Tpo -c -o objc_extension.o objc_extension.cc
mv -f .deps/objc_extension.Tpo .deps/objc_extension.Po
g++ -DHAVE_CONFIG_H -I. -I../.. -I/usr/local/include -MT objc_helpers.o -MD -MP -MF .deps/objc_helpers.Tpo -c -o objc_helpers.o objc_helpers.cc
mv -f .deps/objc_helpers.Tpo .deps/objc_helpers.Po
g++ -DHAVE_CONFIG_H -I. -I../.. -I/usr/local/include -MT objc_field.o -MD -MP -MF .deps/objc_field.Tpo -c -o objc_field.o objc_field.cc
mv -f .deps/objc_field.Tpo .deps/objc_field.Po
g++ -DHAVE_CONFIG_H -I. -I../.. -I/usr/local/include -MT objc_message.o -MD -MP -MF .deps/objc_message.Tpo -c -o objc_message.o objc_message.cc
mv -f .deps/objc_message.Tpo .deps/objc_message.Po
g++ -DHAVE_CONFIG_H -I. -I../.. -I/usr/local/include -MT objectivec-descriptor.pb.o -MD -MP -MF .deps/objectivec-descriptor.pb.Tpo -c -o objectivec-descriptor.pb.o `test -f 'google/protobuf/objectivec-descriptor.pb.cc' || echo './'`google/protobuf/objectivec-descriptor.pb.cc
mv -f .deps/objectivec-descriptor.pb.Tpo .deps/objectivec-descriptor.pb.Po
/bin/sh ../../libtool --tag=CXX --mode=link g++ -I/usr/local/include -lprotobuf -lprotoc -L/usr/local/lib -o protoc-gen-objc main.o objc_enum_field.o objc_file.o objc_message_field.o objc_enum.o objc_generator.o objc_primitive_field.o objc_extension.o objc_helpers.o objc_field.o objc_message.o objectivec-descriptor.pb.o
libtool: link: g++ -I/usr/local/include -o protoc-gen-objc main.o objc_enum_field.o objc_file.o objc_message_field.o objc_enum.o objc_generator.o objc_primitive_field.o objc_extension.o objc_helpers.o objc_field.o objc_message.o objectivec-descriptor.pb.o -Wl,-bind_at_load -lprotobuf -lprotoc -L/usr/local/lib
make[2]: Nothing to be done for `all-am’.
make install
Making install in src/compiler
../.././install-sh -c -d '/usr/local/bin'
/bin/sh ../../libtool --mode=install /usr/bin/install -c protoc-gen-objc '/usr/local/bin'
libtool: install: /usr/bin/install -c protoc-gen-objc /usr/local/bin/protoc-gen-objc
make[2]: Nothing to be done for `install-data-am'.
make[2]: Nothing to be done for `install-exec-am'.
make[2]: Nothing to be done for `install-data-am’.
创建proto文件
先在桌面创建一个文件夹,文件夹更名为ProtoBuf
cd ~/Desktop/ProtoBuf
touch person.proto
vi person.proto
proto的文件内容示例:
package web.platform;
message login_account_request
{
required bytes account = 1;
optional bytes passwd = 2;
}
message login_account_response
{
required int32 ec = 1;
optional bytes token = 2;
}
然后保存退出(按esc,输入:wq)
这样就在ProtoBuf的文件夹下面生成了proto文件,MAC默认没有可以打开这个文本文件的,所以选择TextEdit.app进行打开,你可以看到文件内容
注意:proto的内容格式一定要正确,可以将自己创建出来的文本格式和示例的进行对比,package有没有拼写错误,需要分号的地方是否有分号,包括大括号的格式。如果内容格式有问题,可能会导致后面无法生成正确的OC文件
生成OC文件
cd ~/Desktop/ProtoBuf
protoc --plugin=/usr/local/bin/protoc-gen-objc person.proto --objc_out="./"
这样,就在ProtoBuf的文件夹下面生成了OC文件
工程中Protobuf的应用
做了那么多铺垫,说了那么多废话,我们的核心部分终于来了
首先新建一个工程(假设工程名为TestProtoc),并且用CocoaPod在工程中配置ProtocolBuffer
cd~/Desktop/TestProtoc
pod init
打开Podfile文件
输入
pod "ProtocolBuffers", "~> 1.9.7”
关闭Podfile继续在terminal输入
pod install
然后终于可以不理terminal了,我们进入工程做事
先把生成的OC文件导入到工程中,我们以get和post两种网络数据方式进行示例
在ViewController.m文件中导入以下文件
#import <ProtocolBuffers/ProtocolBuffers.h>
#import "Web_test.pb.h"
Get方式
- (void)protoGet
{
NSData *raw_data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"此处填写url"]];
login_account_response *response = [[login_account_response alloc]init];
response = [login_account_response parseFromData:raw_data];
NSLog(@"=====%@",response);
NSLog(@"----- %@", [[NSString alloc]initWithData:response.token encoding:NSUTF8StringEncoding]);
}
Post方式
- (void)protoPost
{
NSURL *url = [NSURL URLWithString:@"此处填写url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.timeoutInterval = 0.5;
request.HTTPMethod = @"POST";
// 设置请求体
login_account_requestBuilder *builder = [login_account_request builder];
NSString *accountStr = [NSString stringWithFormat:@"hello"];
NSString *passwdStr = [NSString stringWithFormat:@"123"];
builder.account = [accountStr dataUsingEncoding:NSUTF8StringEncoding];
builder.passwd = [passwdStr dataUsingEncoding:NSUTF8StringEncoding];
login_account_request *req = [builder build];
NSLog(@"%@",[req data]);
request.HTTPBody = [req data];
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);
}
else
{
NSLog(@"------ data = %@",data);
NSLog(@"success");
// 返回的数据
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
}
}];
[task resume];
}
转载自http://www.zuimoban.com/jiaocheng/ios/2016/0107/2656.html
相关文章http://blog.cocoachina.com/article/12647