blob: 5e7abf3685c7c367832e66bad72a98b6202a689d [file] [log] [blame] [view]
Jorge Canizales5436cf12015-06-08 23:06:54 -07001#gRPC Basics: Objective-C
2
3This tutorial provides a basic Objective-C programmer's introduction to working with gRPC. By walking through this example you'll learn how to:
4
5- Define a service in a .proto file.
6- Generate client code using the protocol buffer compiler.
7- Use the Objective-C gRPC API to write a simple client for your service.
8
9It assumes a passing familiarity with [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, which is currently in alpha release: you can find out more in the [proto3 language guide](https://developers.google.com/protocol-buffers/docs/proto3) and see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository.
10
11This isn't a comprehensive guide to using gRPC in Objective-C: more reference documentation is coming soon.
12
13- [Why use gRPC?](#why-grpc)
14- [Example code and setup](#setup)
15- [Try it out!](#try)
16- [Defining the service](#proto)
17- [Generating client code](#protoc)
18- [Creating the client](#client)
19
20<a name="why-grpc"></a>
21## Why use gRPC?
22
23With gRPC you can define your service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. You also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating.
24
25gRPC and proto3 are specially suited for mobile clients: gRPC is implemented on top of HTTP/2, which results in network bandwidth savings over using HTTP/1.1. Serialization and parsing of the proto binary format is more efficient than the equivalent JSON, resulting in CPU and battery savings. And proto3 uses a runtime that has been optimized over the years at Google to keep code size to a minimum. The latter is important in Objective-C, because the ability of the compiler to strip unused code is limited by the dynamic nature of the language.
26
27
28<a name="setup"></a>
29## Example code and setup
30
31The example code for our tutorial is in [grpc/grpc-common/objective-c/route_guide](https://github.com/grpc/grpc-common/tree/master/objective-c/route_guide). To download the example, clone the `grpc-common` repository by running the following command:
32```shell
33$ git clone https://github.com/grpc/grpc-common.git
34```
35
36Then change your current directory to `grpc-common/objective-c/route_guide`:
37```shell
38$ cd grpc-common/objective-c/route_guide
39```
40
41Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients.
42
43You also should have [Cocoapods](https://cocoapods.org/#install) installed, as well as the relevant tools to generate the client library code (and a server in another language, for testing). You can obtain the latter by following [these setup instructions](https://github.com/grpc/homebrew-grpc).
44
45
46<a name="try"></a>
47## Try it out!
48
49To try the sample app, we need a gRPC server running locally. Let's compile and run, for example, the C++ server in this repository:
50
51```shell
52$ pushd ../../cpp/route_guide
53$ make
54$ ./route_guide_server &
55$ popd
56```
57
58Now have Cocoapods generate and install the client library for our .proto files:
59
60```shell
61$ pod install
62```
63
64(This might have to compile OpenSSL, which takes around 15 minutes if Cocoapods doesn't have it yet on your computer's cache).
65
66Finally, open the XCode workspace created by Cocoapods, and run the app. You can check the calling code in `ViewControllers.m` and see the results in XCode's log console.
67
68The next sections guide you step-by-step through the creation of this proto service, the client library generated from it, and the app that uses that library.
69
70
71<a name="proto"></a>
72## Defining the service
73
74Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc-common)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`grpc-common/protos/route_guide.proto`](https://github.com/grpc/grpc-common/blob/master/protos/route_guide.proto).
75
76To define a service, you specify a named `service` in your .proto file:
77
78```protobuf
79service RouteGuide {
80 ...
81}
82```
83
84Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service:
85
86- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call.
87```protobuf
88 // Obtains the feature at a given position.
89 rpc GetFeature(Point) returns (Feature) {}
90```
91
92- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type.
93```protobuf
94 // Obtains the Features available within the given Rectangle. Results are
95 // streamed rather than returned at once (e.g. in a response message with a
96 // repeated field), as the rectangle may cover a large area and contain a
97 // huge number of features.
98 rpc ListFeatures(Rectangle) returns (stream Feature) {}
99```
100
101- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a client-side streaming method by placing the `stream` keyword before the *request* type.
102```protobuf
103 // Accepts a stream of Points on a route being traversed, returning a
104 // RouteSummary when traversal is completed.
105 rpc RecordRoute(stream Point) returns (RouteSummary) {}
106```
107
108- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response.
109```protobuf
110 // Accepts a stream of RouteNotes sent while a route is being traversed,
111 // while receiving other RouteNotes (e.g. from other users).
112 rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
113```
114
115Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type:
116```protobuf
117// Points are represented as latitude-longitude pairs in the E7 representation
118// (degrees multiplied by 10**7 and rounded to the nearest integer).
119// Latitudes should be in the range +/- 90 degrees and longitude should be in
120// the range +/- 180 degrees (inclusive).
121message Point {
122 int32 latitude = 1;
123 int32 longitude = 2;
124}
125```
126
127<a name="protoc"></a>
128## Generating client code
129
130Next we need to generate the gRPC client interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC Objective-C plugin.
131
132For simplicity, we've provided a [Podspec file](https://github.com/grpc/grpc-common/blob/master/objective-c/route_guide/RouteGuide.podspec) that runs `protoc` for you with the appropriate plugin, input, and output, and describes how to compile the generated files. You just need to run in this directory:
133
134```shell
135$ pod install
136```
137
138which, before installing the generated library in the XCode project of this sample, runs:
139
140```shell
141$ protoc -I ../../protos --objc_out=Pods/RouteGuide --objcgrpc_out=Pods/RouteGuide ../../protos/route_guide.proto
142```
143
144Running this command generates the following files in under `Pods/RouteGuide/`:
145- `RouteGuide.pbobjc.h`, the header which declares your generated message classes
146- `RouteGuide.pbobjc.m`, which contains the implementation of your message classes
147- `RouteGuide.pbrpc.h`, the header which declares your generated service classes
148- `RouteGuide.pbrpc.m`, which contains the implementation of your service classes
149
150These contain:
151- All the protocol buffer code to populate, serialize, and retrieve our request and response message types
152- A class called `RTGRouteGuide` that for clients to call with the methods defined in the `RouteGuide` service.
153
154
155<a name="client"></a>
156## Creating the client
157
158In this section, we'll look at creating an Objective-C client for our `RouteGuide` service. You can see our complete example client code in [grpc-common/objective-c/route_guide/ViewControllers.m](https://github.com/grpc/grpc-common/blob/master/objective-c/route_guide/ViewControllers.m). (Note: In your apps, for maintainability and readability reasons, you shouldn't put all of your view controllers in a single file; it's done here only to simplify the learning process).
159
160### Creating a client object
161
162To call service methods, we first need to create a client object, an instance of the generated `RTGRouteGuide` class. The designated initializer of the class expects a `NSString *` with the server address and port we want to connect to:
163
164```objective-c
165#import <RouteGuide/RouteGuide.pbrpc.h>
166
167static NSString * const kHostAddress = @"http://localhost:50051";
168
169...
170
171RTGRouteGuide *client = [[RTGRouteGuide alloc] initWithHost:kHostAddress];
172```
173
174Notice that we've specified the HTTP scheme in the host address. This is because the server we will be using to test our client doesn't use [TLS](http://en.wikipedia.org/wiki/Transport_Layer_Security). This is fine because it will be running locally on our development machine. The most common case, though, is connecting with a gRPC server on the internet, running gRPC over TLS. For that case, the HTTPS scheme can be specified (or no scheme at all, as HTTPS is the default value).
175
176
177### Calling service methods
178
179Now let's look at how we call our service methods. As you will see, all these methods are asynchronous, so you can call them from the main thread of your app without worrying about freezing your UI or the OS killing your app.
180
181#### Simple RPC
182
183Calling the simple RPC `GetFeature` is nearly as straightforward as calling any other aynschronous method on Cocoa.
184
185```objective-c
186RTGPoint *point = [RTGPoint message];
187point.latitude = 40E7;
188point.longitude = -74E7;
189
190[client getFeatureWithRequest:point handler:^(RTGFeature *response, NSError *error) {
191 if (response) {
192 // Successful response received
193 } else {
194 // RPC error
195 }
196}];
197```
198
199As you can see, we create and populate a request protocol buffer object (in our case `RTGPoint`). Then, we call the method on the client object, passing it the request, and a block to handle the response (or any RPC error). If the RPC finished successfully, the handler block is called with a `nil` error argument, and we can read the response information from the server from the response argument. If, instead, some RPC error happened, the handler block is called with a `nil` response argument, and we can read the details of the problem from the error argument.
200
201```objective-c
202NSLog(@"Found feature called %@ at %@.", response.name, response.location);
203```
204
205#### Streaming RPCs
206
207Now let's look at our streaming methods. Here's where we call the response-streaming method `ListFeatures`, which results in our client receiving a stream of geographical `RTGFeature`s:
208
209```objective-c
210[client listFeaturesWithRequest:rectangle handler:^(BOOL done, RTGFeature *response, NSError *error) {
211 if (response) {
212 // Element of the stream of responses received
213 } else if (error) {
214 // RPC error; the stream is over.
215 }
216 if (done) {
217 // The stream is over (all the responses were received, or an error occured). Do any cleanup.
218 }
219}];
220```
221
222Notice how the signature of the handler block now includes a `BOOL done` parameter. The block will be called any number of times; only on the last call will the `done` argument be `YES`. If an error occurs, the RPC will be finished and the handler will be called with arguments `(YES, nil, error)`.
223
224The request-streaming method `RecordRoute` expects a stream of `RTGPoint`s from the cient. This stream is passed to the method as an object that conforms to the `GRXWriter` protocol. The simplest way to create one is to initialize one from a `NSArray` object:
225
226
227```objective-c
228#import <gRPC/GRXWriter+Immediate.h>
229
230...
231
232RTGPoint *point1 = [RTGPoint message];
233point.latitude = 40E7;
234point.longitude = -74E7;
235
236RTGPoint *point2 = [RTGPoint message];
237point.latitude = 40E7;
238point.longitude = -74E7;
239
240GRXWriter *locationsWriter = [GRXWriter writerWithContainer:@[point1, point2]];
241
242[client recordRouteWithRequestsWriter:locationsWriter handler:^(RTGRouteSummary *response, NSError *error) {
243 if (response) {
244 NSLog(@"Finished trip with %i points", response.pointCount);
245 NSLog(@"Passed %i features", response.featureCount);
246 NSLog(@"Travelled %i meters", response.distance);
247 NSLog(@"It took %i seconds", response.elapsedTime);
248 } else {
249 NSLog(@"RPC error: %@", error);
250 }
251}];
252
253```
254
255The `GRXWriter` protocol is generic enough to allow for asynchronous streams, streams of future values, or even infinite streams.
256
257Finally, let's look at our bidirectional streaming RPC `RouteChat()`. The way to call a bidirectional streaming RPC is just a combination of how to call request-streaming RPCs and response-streaming RPCs.
258
259```objective-c
260[client routeChatWithRequestsWriter:notesWriter handler:^(BOOL done, RTGRouteNote *note, NSError *error) {
261 if (note) {
262 NSLog(@"Got message %@ at %@", note.message, note.location);
263 } else if (error) {
264 NSLog(@"RPC error: %@", error);
265 }
266 if (done) {
267 NSLog(@"Chat ended.");
268 }
269}];
270```
271
272The semantics for the handler block and the `GRXWriter` argument here are exactly the same as for our request-streaming and response-streaming methods. Although both client and server will always get the other's messages in the order they were written, the two streams operate completely independently.