gRPC Basics - Objective-C

This tutorial provides a basic Objective-C programmer’sintroduction to working with gRPC.

By walking through this example you’ll learn how to:

  • Define a service in a .proto file.
  • Generate client code using the protocol buffer compiler.
  • Use the Objective-C gRPC API to write a simple client for your service.

It assumes a passing familiarity withprotocolbuffers. Notethat the example in this tutorial uses the proto3 version of the protocolbuffers language: you can find out more intheproto3 languageguide and theObjective-C generated codeguide.

Why use gRPC?

With gRPC you can define your service once in a .proto file and implementclients and servers in any of gRPC’s supported languages, which in turn can berun in environments ranging from servers inside Google to your own tablet - allthe complexity of communication between different languages and environments ishandled for you by gRPC. You also get all the advantages of working withprotocol buffers, including efficient serialization, a simple IDL, and easyinterface updating.

gRPC and proto3 are specially suited for mobile clients: gRPC is implemented ontop 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 theequivalent JSON, resulting in CPU and battery savings. And proto3 uses a runtimethat 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 tostrip unused code is limited by the dynamic nature of the language.

Example code and setup

The example code for our tutorial is ingrpc/grpc/examples/objective-c/route_guide.To download the example, clone the grpc repository by running the followingcommands:

  1. $ git clone -b v1.28.1 https://github.com/grpc/grpc
  2. $ cd grpc
  3. $ git submodule update --init

Then change your current directory to examples/objective-c/route_guide:

  1. $ cd examples/objective-c/route_guide

Our example is a simple route mapping application that lets clients getinformation about features on their route, create a summary of their route, andexchange route information such as traffic updates with the server and otherclients.

You also should haveCocoapods installed, aswell as the relevant tools to generate the client library code (and a server inanother language, for testing). You can obtain the latter by followingthesesetup instructions.

Try it out!

To try the sample app, we need a gRPC server running locally. Let’s compile andrun, for example, the C++ server in this repository:

  1. $ pushd ../../cpp/route_guide
  2. $ make
  3. $ ./route_guide_server &
  4. $ popd

Now have Cocoapods generate and install the client library for our .proto files:

  1. $ pod install

(This might have to compile OpenSSL, which takes around 15 minutes if Cocoapodsdoesn’t have it yet on your computer’s cache).

Finally, open the XCode workspace created by Cocoapods, and run the app. You cancheck the calling code in ViewControllers.m and see the results in XCode’s logconsole.

The next sections guide you step-by-step through how this proto service isdefined, how to generate a client library from it, and how to create an app thatuses that library.

Defining the service

First let’s look at how the service we’re using is defined. A gRPC service andits method request and response types usingprotocolbuffers. You cansee the complete .proto file for our example inexamples/protos/route_guide.proto.

To define a service, you specify a named service in your .proto file:

  1. service RouteGuide {
  2. ...
  3. }

Then you define rpc methods inside your service definition, specifying theirrequest and response types. Protocol buffers let you define four kinds ofservice method, all of which are used in the RouteGuide service:

  • A simple RPC where the client sends a request to the server and receives aresponse later, just like a normal remote procedure call.
  1. // Obtains the feature at a given position.
  2. rpc GetFeature(Point) returns (Feature) {}
  • A response-streaming RPC where the client sends a request to the server andgets back a stream of response messages. You specify a response-streamingmethod by placing the stream keyword before the response type.
  1. // Obtains the Features available within the given Rectangle. Results are
  2. // streamed rather than returned at once (e.g. in a response message with a
  3. // repeated field), as the rectangle may cover a large area and contain a
  4. // huge number of features.
  5. rpc ListFeatures(Rectangle) returns (stream Feature) {}
  • A request-streaming RPC where the client sends a sequence of messages to theserver. Once the client has finished writing the messages, it waits for theserver to read them all and return its response. You specify arequest-streaming method by placing the stream keyword before the _request_type.
  1. // Accepts a stream of Points on a route being traversed, returning a
  2. // RouteSummary when traversal is completed.
  3. rpc RecordRoute(stream Point) returns (RouteSummary) {}
  • A bidirectional streaming RPC where both sides send a sequence of messagesto the other. The two streams operate independently, so clients and serverscan read and write in whatever order they like: for example, the server couldwait to receive all the client messages before writing its responses, or itcould alternately read a message then write a message, or some othercombination of reads and writes. The order of messages in each stream ispreserved. You specify this type of method by placing the stream keywordbefore both the request and the response.
  1. // Accepts a stream of RouteNotes sent while a route is being traversed,
  2. // while receiving other RouteNotes (e.g. from other users).
  3. rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}

Our .proto file also contains protocol buffer message type definitions for allthe request and response types used in our service methods - for example, here’sthe Point message type:

  1. // Points are represented as latitude-longitude pairs in the E7 representation
  2. // (degrees multiplied by 10**7 and rounded to the nearest integer).
  3. // Latitudes should be in the range +/- 90 degrees and longitude should be in
  4. // the range +/- 180 degrees (inclusive).
  5. message Point {
  6. int32 latitude = 1;
  7. int32 longitude = 2;
  8. }

You can specify a prefix to be used for your generated classes by adding theobjc_class_prefix option at the top of the file. For example:

  1. option objc_class_prefix = "RTG";

Generating client code

Next we need to generate the gRPC client interfaces from our .proto servicedefinition. We do this using the protocol buffer compiler (protoc) with aspecial gRPC Objective-C plugin.

For simplicity, we’ve provided aPodspecfilethat runs protoc for you with the appropriate plugin, input, and output, anddescribes how to compile the generated files. You just need to run in thisdirectory (examples/objective-c/route_guide):

  1. $ pod install

which, before installing the generated library in the XCode project of this sample, runs:

  1. $ protoc -I ../../protos --objc_out=Pods/RouteGuide --objcgrpc_out=Pods/RouteGuide ../../protos/route_guide.proto

Running this command generates the following files under Pods/RouteGuide/:

  • RouteGuide.pbobjc.h, the header which declares your generated messageclasses.
  • RouteGuide.pbobjc.m, which contains the implementation of your messageclasses.
  • RouteGuide.pbrpc.h, the header which declares your generated serviceclasses.
  • RouteGuide.pbrpc.m, which contains the implementation of your serviceclasses.

These contain:

  • All the protocol buffer code to populate, serialize, and retrieve our requestand response message types.
  • A class called RTGRouteGuide that lets clients call the methods defined inthe RouteGuide service.

You can also use the provided Podspec file to generate client code from anyother proto service definition; just replace the name (matching the file name),version, and other metadata.

Creating the client application

In this section, we’ll look at creating an Objective-C client for ourRouteGuide service. You can see our complete example client code inexamples/objective-c/route_guide/ViewControllers.m.

Note

In your apps, for maintainability and readability reasons, you shouldn’tput all of your view controllers in a single file; it’s done here only tosimplify the learning process).

Constructing a service object

To call service methods, we first need to create a service object, an instanceof the generated RTGRouteGuide class. The designated initializer of the classexpects a NSString * with the server address and port we want to connect to:

  1. #import <GRPCClient/GRPCCall+Tests.h>
  2. #import <RouteGuide/RouteGuide.pbrpc.h>
  3. #import <GRPCClient/GRPCTransport.h>
  4. static NSString * const kHostAddress = @"localhost:50051";
  5. ...
  6. GRPCMutableCallOptions *options = [[GRPCMutableCallOptions alloc] init];
  7. options.transport = GRPCDefaultTransportImplList.core_insecure;
  8. RTGRouteGuide *service = [[RTGRouteGuide alloc] initWithHost:kHostAddress callOptions:options];

Notice that we our service is constructed with an insecure transport. This isbecause the server we will be using to test our client doesn’t useTLS. This is finebecause it will be running locally on our development machine. The most commoncase, though, is connecting with a gRPC server on the internet, running gRPCover TLS. For that case, the setting the option options.transport isn’tneeded because gRPC will use a secure TLS transport by default.

Calling service methods

Now let’s look at how we call our service methods. As you will see, all thesemethods are asynchronous, so you can call them from the main thread of your appwithout worrying about freezing your UI or the OS killing your app.

Simple RPC

Calling the simple RPC GetFeature is as straightforward as calling any otherasynchronous method on Cocoa.

  1. RTGPoint *point = [RTGPoint message];
  2. point.latitude = 40E7;
  3. point.longitude = -74E7;
  4. GRPCUnaryResponseHandler *handler =
  5. [[GRPCUnaryResponseHandler alloc] initWithResponseHandler:
  6. ^(RTGFeature *response, NSError *error) {
  7. if (response) {
  8. // Successful response received
  9. } else {
  10. // RPC error
  11. }
  12. }
  13. responseDispatchQueue:nil];
  14. [[service getFeatureWithMessage:point responseHandler:handler callOptions:nil] start];

As you can see, we create and populate a request protocol buffer object (in ourcase RTGPoint). Then, we call the method on the service object, passing it therequest, and a block to handle the response (or any RPC error). If the RPCfinishes successfully, the handler block is called with a nil error argument,and we can read the response information from the server from the responseargument. If, instead, some RPC error happens, the handler block is called witha nil response argument, and we can read the details of the problem from theerror argument.

Streaming RPCs

Now let’s look at our streaming methods. Here’s where we call theresponse-streaming method ListFeatures, which results in our client appreceiving a stream of geographical RTGFeatures:

  1. - (void)didReceiveProtoMessage(GPBMessage *)message {
  2. if (message) {
  3. NSLog(@"Found feature at %@ called %@.", response.location, response.name);
  4. }
  5. }
  6. - (void)didCloseWithTrailingMetadata:(NSDictionary *)trailingMetadata error:(NSError *)error {
  7. if (error) {
  8. NSLog(@"RPC error: %@", error);
  9. }
  10. }
  11. - (void)execRequest {
  12. ...
  13. [[service listFeaturesWithMessage:rectangle responseHandler:self callOptions:nil] start];
  14. }

Notice that instead of providing a response handler object, the view controllerobject itself handles the responses. The method didReceiveProtoMessage: iscalled when there’s a message received; it can be called any number of times.The method didCloseWithTrailingMetadata: is called when the call is completeand the gRPC status is received from the server (or when there’s any errorhappens during the call).

The request-streaming method RecordRoute expects a stream of RTGPoints fromthe cient. This stream can be written to the gRPC call object after the callstarts.

  1. RTGPoint *point1 = [RTGPoint message];
  2. point.latitude = 40E7;
  3. point.longitude = -74E7;
  4. RTGPoint *point2 = [RTGPoint message];
  5. point.latitude = 40E7;
  6. point.longitude = -74E7;
  7. GRPCUnaryResponseHandler *handler =
  8. [[GRPCUnaryResponseHandler alloc] initWithResponseHandler:
  9. ^(RTGRouteSummary *response, NSError *error) {
  10. if (response) {
  11. NSLog(@"Finished trip with %i points", response.pointCount);
  12. NSLog(@"Passed %i features", response.featureCount);
  13. NSLog(@"Travelled %i meters", response.distance);
  14. NSLog(@"It took %i seconds", response.elapsedTime);
  15. } else {
  16. NSLog(@"RPC error: %@", error);
  17. }
  18. }
  19. responseDispatchQueue:nil];
  20. GRPCStreamingProtoCall *call =
  21. [service recordRouteWithResponseHandler:handler callOptions:nil];
  22. [call start];
  23. [call writeMessage:point1];
  24. [call writeMessage:point2];
  25. [call finish];

Note that since the gRPC call object does not know the end of the requeststream, users must invoke finish: method when the request stream is complete.

Finally, let’s look at our bidirectional streaming RPC RouteChat(). The way tocall a bidirectional streaming RPC is just a combination of how to callrequest-streaming RPCs and response-streaming RPCs.

  1. - (void)didReceiveProtoMessage(GPBMessage *)message {
  2. RTGRouteNote *note = (RTGRouteNote *)message;
  3. if (note) {
  4. NSLog(@"Got message %@ at %@", note.message, note.location);
  5. }
  6. }
  7. - (void)didCloseWithTrailingMetadata:(NSDictionary *)trailingMetadata error:(NSError *)error {
  8. if (error) {
  9. NSLog(@"RPC error: %@", error);
  10. } else {
  11. NSLog(@"Chat ended.");
  12. }
  13. }
  14. - (void)execRequest {
  15. ...
  16. GRPCStreamingProtoCall *call =
  17. [service routeChatWithResponseHandler:self callOptions:nil];
  18. [call start];
  19. [call writeMessage:note1];
  20. ...
  21. [call writeMessage:noteN];
  22. [call finish];
  23. }