Merge pull request #264 from jcanizales/update-to-0.6

Update ObjC samples to v0.6
pull/3109/head
Michael Lumish 10 years ago
commit 94390e2647
  1. 5
      grpc-auth-support.md
  2. 2
      objective-c/auth_sample/AuthTestService.podspec
  3. 39
      objective-c/auth_sample/MakeRPCViewController.m
  4. 38
      objective-c/auth_sample/README.md
  5. 2
      objective-c/helloworld/HelloWorld.podspec
  6. 131
      objective-c/helloworld/HelloWorld.xcodeproj/project.pbxproj
  7. 3
      objective-c/helloworld/HelloWorld/AppDelegate.h
  8. 1
      objective-c/helloworld/HelloWorld/AppDelegate.m
  9. 40
      objective-c/helloworld/HelloWorld/ViewController.h
  10. 6
      objective-c/helloworld/HelloWorld/ViewController.m
  11. 26
      objective-c/helloworld/README.md
  12. 162
      objective-c/route_guide/README.md
  13. 2
      objective-c/route_guide/RouteGuide.podspec
  14. 10
      objective-c/route_guide/ViewControllers.m

@ -247,7 +247,7 @@ GIDSignIn.sharedInstance.scopes = @[@"https://www.googleapis.com/auth/grpc-testi
...
#import <gRPC/ProtoRPC.h>
#import <ProtoRPC/ProtoRPC.h>
// Create a not-yet-started RPC. We want to set the request headers on this object before starting
// it.
@ -258,8 +258,7 @@ ProtoRPC *call =
// Set the access token to be used.
NSString *accessToken = GIDSignIn.sharedInstance.currentUser.authentication.accessToken;
call.requestMetadata = [NSMutableDictionary dictionaryWithDictionary:
@{@"Authorization": [@"Bearer " stringByAppendingString:accessToken]}];
call.requestMetadata[@"Authorization"] = [@"Bearer " stringByAppendingString:accessToken]}];
// Start the RPC.
[call start];

@ -29,7 +29,7 @@ Pod::Spec.new do |s|
ss.source_files = "#{dir}/*.pbrpc.{h,m}", "#{dir}/**/*.pbrpc.{h,m}"
ss.header_mappings_dir = dir
ss.requires_arc = true
ss.dependency "gRPC", "~> 0.5"
ss.dependency "gRPC", "~> 0.6"
ss.dependency "#{s.name}/Messages"
end
end

@ -35,13 +35,33 @@
#import <AuthTestService/AuthSample.pbrpc.h>
#import <Google/SignIn.h>
#import <gRPC/ProtoRPC.h>
#include <gRPC/status.h>
#include <grpc/status.h>
#import <ProtoRPC/ProtoRPC.h>
NSString * const kTestScope = @"https://www.googleapis.com/auth/xapi.zoo";
static NSString * const kTestHostAddress = @"grpc-test.sandbox.google.com";
// Category for RPC errors to create the descriptions as we want them to appear on our view.
@interface NSError (AuthSample)
- (NSString *)UIDescription;
@end
@implementation NSError (AuthSample)
- (NSString *)UIDescription {
if (self.code == GRPC_STATUS_UNAUTHENTICATED) {
// Authentication error. OAuth2 specifies we'll receive a challenge header.
// |userInfo[kGRPCStatusMetadataKey]| is the dictionary of response metadata.
NSString *challengeHeader = self.userInfo[kGRPCStatusMetadataKey][@"www-authenticate"] ?: @"";
return [@"Invalid credentials. Server challenge:\n" stringByAppendingString:challengeHeader];
} else {
// Any other error.
return [NSString stringWithFormat:@"Unexpected RPC error %li: %@",
(long)self.code, self.localizedDescription];
}
}
@end
@implementation MakeRPCViewController
- (void)viewWillAppear:(BOOL)animated {
@ -55,30 +75,21 @@ static NSString * const kTestHostAddress = @"grpc-test.sandbox.google.com";
// Create a not-yet-started RPC. We want to set the request headers on this object before starting
// it.
__block ProtoRPC *call =
ProtoRPC *call =
[client RPCToUnaryCallWithRequest:request handler:^(AUTHResponse *response, NSError *error) {
if (response) {
// This test server responds with the email and scope of the access token it receives.
self.mainLabel.text = [NSString stringWithFormat:@"Used scope: %@ on behalf of user %@",
response.oauthScope, response.username];
} else if (error.code == GRPC_STATUS_UNAUTHENTICATED) {
// Authentication error. OAuth2 specifies we'll receive a challenge header.
NSString *challengeHeader = call.responseMetadata[@"www-authenticate"][0] ?: @"";
self.mainLabel.text =
[@"Invalid credentials. Server challenge:\n" stringByAppendingString:challengeHeader];
} else {
// Any other error.
self.mainLabel.text = [NSString stringWithFormat:@"Unexpected RPC error %li: %@",
(long)error.code, error.localizedDescription];
self.mainLabel.text = error.UIDescription;
}
}];
// Set the access token to be used.
NSString *accessToken = GIDSignIn.sharedInstance.currentUser.authentication.accessToken;
call.requestMetadata = [NSMutableDictionary dictionaryWithDictionary:
@{@"Authorization": [@"Bearer " stringByAppendingString:accessToken]}];
call.requestMetadata[@"Authorization"] = [@"Bearer " stringByAppendingString:accessToken];
// Start the RPC.
[call start];

@ -115,7 +115,7 @@ In addition, an `RPCToUnaryCallWithRequest:handler:` method is generated, which
not-yet-started RPC object:
```objective-c
#import <gRPC/ProtoRPC.h>
#import <ProtoRPC/ProtoRPC.h>
ProtoRPC *call =
[client RPCToUnaryCallWithRequest:request handler:^(AUTHResponse *response, NSError *error) {
@ -132,10 +132,11 @@ The RPC represented by this object can be started at any later time like this:
<a name="request-metadata"></a>
## Set request metadata of a call: Authorization header with an access token
The `ProtoRPC` class has a `requestMetadata` property defined like this:
The `ProtoRPC` class has a `requestMetadata` property (inherited from `GRPCCall`) defined like this:
```objective-c
@property(nonatomic, readwrite) NSMutableDictionary *requestMetadata;
- (NSMutableDictionary *)requestMetadata; // nonatomic
- (void)setRequestMetadata:(NSDictionary *)requestMetadata; // nonatomic, copy
```
Setting it to a dictionary of metadata keys and values will have them sent on the wire when the call
@ -143,33 +144,46 @@ is started. gRPC metadata are pieces of information about the call sent by the c
(and vice versa). They take the form of key-value pairs and are essentially opaque to gRPC itself.
```objective-c
call.requestMetadata = [NSMutableDictionary dictionaryWithDictionary:
@{@"My-Header": @"Value for this header",
@"Another-Header": @"Its value"}];
call.requestMetadata = @{@"My-Header": @"Value for this header",
@"Another-Header": @"Its value"};
```
For convenience, the property is initialized with an empty `NSMutableDictionary`, so that request
metadata elements can be set like this:
```objective-c
call.requestMetadata[@"My-Header"] = @"Value for this header";
```
If you have an access token, OAuth2 specifies it is to be sent in this format:
```objective-c
@{@"Authorization": [@"Bearer " stringByAppendingString:accessToken]}
call.requestMetadata[@"Authorization"] = [@"Bearer " stringByAppendingString:accessToken];
```
<a name="response-metadata"></a>
## Get response metadata of a call: Auth challenge header
The `ProtoRPC` class also has a `responseMetadata` property, analogous to the request metadata we
just looked at. It's defined like this:
The `ProtoRPC` class also inherits a `responseMetadata` property, analogous to the request metadata
we just looked at. It's defined like this:
```objective-c
@property(atomic, readonly) NSDictionary *responseMetadata;
```
Because gRPC metadata keys can be repeated, the values of the `responseMetadata` dictionary are
always `NSArray`s. Thus, to access OAuth2's authentication challenge header you write:
To access OAuth2's authentication challenge header you write:
```objective-c
call.responseMetadata[@"www-authenticate"][0]
call.responseMetadata[@"www-authenticate"]
```
Note that, as gRPC metadata elements are mapped to HTTP/2 headers (or trailers), the keys of the
response metadata are always ASCII strings in lowercase.
Many uses cases of response metadata are getting more details about an RPC error. For convenience,
when a `NSError` instance is passed to an RPC handler block, the response metadata dictionary can
also be accessed this way:
```objective-c
error.userInfo[kGRPCStatusMetadataKey]
```

@ -29,7 +29,7 @@ Pod::Spec.new do |s|
ss.source_files = "#{dir}/*.pbrpc.{h,m}", "#{dir}/**/*.pbrpc.{h,m}"
ss.header_mappings_dir = dir
ss.requires_arc = true
ss.dependency "gRPC", "~> 0.5"
ss.dependency "gRPC", "~> 0.6"
ss.dependency "#{s.name}/Messages"
end
end

@ -12,20 +12,9 @@
5E36906C1B2A23800040F884 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 5E36906B1B2A23800040F884 /* ViewController.m */; };
5E36906F1B2A23800040F884 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 5E36906D1B2A23800040F884 /* Main.storyboard */; };
5E3690711B2A23800040F884 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 5E3690701B2A23800040F884 /* Images.xcassets */; };
5E3690801B2A23800040F884 /* HelloWorldTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 5E36907F1B2A23800040F884 /* HelloWorldTests.m */; };
EF61CF6AE2536A31D47F0E63 /* libPods-HelloWorld.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B4E1F55F8A2EC95A0E7EE88 /* libPods-HelloWorld.a */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
5E36907A1B2A23800040F884 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5E3690581B2A23800040F884 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 5E36905F1B2A23800040F884;
remoteInfo = HelloWorld;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
0C432EF610DB15C0F47A66BB /* Pods-HelloWorld.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-HelloWorld.release.xcconfig"; path = "Pods/Target Support Files/Pods-HelloWorld/Pods-HelloWorld.release.xcconfig"; sourceTree = "<group>"; };
5E3690601B2A23800040F884 /* HelloWorld.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = HelloWorld.app; sourceTree = BUILT_PRODUCTS_DIR; };
@ -33,13 +22,9 @@
5E3690651B2A23800040F884 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
5E3690671B2A23800040F884 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
5E3690681B2A23800040F884 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
5E36906A1B2A23800040F884 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = "<group>"; };
5E36906B1B2A23800040F884 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = "<group>"; };
5E36906E1B2A23800040F884 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
5E3690701B2A23800040F884 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = "<group>"; };
5E3690791B2A23800040F884 /* HelloWorldTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = HelloWorldTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
5E36907E1B2A23800040F884 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
5E36907F1B2A23800040F884 /* HelloWorldTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = HelloWorldTests.m; sourceTree = "<group>"; };
6B4E1F55F8A2EC95A0E7EE88 /* libPods-HelloWorld.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-HelloWorld.a"; sourceTree = BUILT_PRODUCTS_DIR; };
DBDE3E48389499064CD664B8 /* Pods-HelloWorld.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-HelloWorld.debug.xcconfig"; path = "Pods/Target Support Files/Pods-HelloWorld/Pods-HelloWorld.debug.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
@ -53,13 +38,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
5E3690761B2A23800040F884 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
@ -68,7 +46,6 @@
children = (
5E3690651B2A23800040F884 /* main.m */,
5E3690621B2A23800040F884 /* HelloWorld */,
5E36907C1B2A23800040F884 /* HelloWorldTests */,
5E3690611B2A23800040F884 /* Products */,
BD9CE6458E7C4FF49A1DF69F /* Pods */,
66CEC7120220DDD2221DD075 /* Frameworks */,
@ -79,7 +56,6 @@
isa = PBXGroup;
children = (
5E3690601B2A23800040F884 /* HelloWorld.app */,
5E3690791B2A23800040F884 /* HelloWorldTests.xctest */,
);
name = Products;
sourceTree = "<group>";
@ -98,7 +74,6 @@
5E3690701B2A23800040F884 /* Images.xcassets */,
5E36906D1B2A23800040F884 /* Main.storyboard */,
5E36906B1B2A23800040F884 /* ViewController.m */,
5E36906A1B2A23800040F884 /* ViewController.h */,
5E3690681B2A23800040F884 /* AppDelegate.m */,
5E3690671B2A23800040F884 /* AppDelegate.h */,
5E3690641B2A23800040F884 /* Info.plist */,
@ -106,23 +81,6 @@
name = "Supporting Files";
sourceTree = "<group>";
};
5E36907C1B2A23800040F884 /* HelloWorldTests */ = {
isa = PBXGroup;
children = (
5E36907F1B2A23800040F884 /* HelloWorldTests.m */,
5E36907D1B2A23800040F884 /* Supporting Files */,
);
path = HelloWorldTests;
sourceTree = "<group>";
};
5E36907D1B2A23800040F884 /* Supporting Files */ = {
isa = PBXGroup;
children = (
5E36907E1B2A23800040F884 /* Info.plist */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
66CEC7120220DDD2221DD075 /* Frameworks */ = {
isa = PBXGroup;
children = (
@ -162,24 +120,6 @@
productReference = 5E3690601B2A23800040F884 /* HelloWorld.app */;
productType = "com.apple.product-type.application";
};
5E3690781B2A23800040F884 /* HelloWorldTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 5E3690861B2A23810040F884 /* Build configuration list for PBXNativeTarget "HelloWorldTests" */;
buildPhases = (
5E3690751B2A23800040F884 /* Sources */,
5E3690761B2A23800040F884 /* Frameworks */,
5E3690771B2A23800040F884 /* Resources */,
);
buildRules = (
);
dependencies = (
5E36907B1B2A23800040F884 /* PBXTargetDependency */,
);
name = HelloWorldTests;
productName = HelloWorldTests;
productReference = 5E3690791B2A23800040F884 /* HelloWorldTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
@ -192,10 +132,6 @@
5E36905F1B2A23800040F884 = {
CreatedOnToolsVersion = 6.2;
};
5E3690781B2A23800040F884 = {
CreatedOnToolsVersion = 6.2;
TestTargetID = 5E36905F1B2A23800040F884;
};
};
};
buildConfigurationList = 5E36905B1B2A23800040F884 /* Build configuration list for PBXProject "HelloWorld" */;
@ -212,7 +148,6 @@
projectRoot = "";
targets = (
5E36905F1B2A23800040F884 /* HelloWorld */,
5E3690781B2A23800040F884 /* HelloWorldTests */,
);
};
/* End PBXProject section */
@ -227,13 +162,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
5E3690771B2A23800040F884 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
@ -280,24 +208,8 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
5E3690751B2A23800040F884 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
5E3690801B2A23800040F884 /* HelloWorldTests.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
5E36907B1B2A23800040F884 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 5E36905F1B2A23800040F884 /* HelloWorld */;
targetProxy = 5E36907A1B2A23800040F884 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
5E36906D1B2A23800040F884 /* Main.storyboard */ = {
isa = PBXVariantGroup;
@ -410,40 +322,6 @@
};
name = Release;
};
5E3690871B2A23810040F884 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
);
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
INFOPLIST_FILE = HelloWorldTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/HelloWorld.app/HelloWorld";
};
name = Debug;
};
5E3690881B2A23810040F884 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
);
INFOPLIST_FILE = HelloWorldTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/HelloWorld.app/HelloWorld";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
@ -465,15 +343,6 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
5E3690861B2A23810040F884 /* Build configuration list for PBXNativeTarget "HelloWorldTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
5E3690871B2A23810040F884 /* Debug */,
5E3690881B2A23810040F884 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 5E3690581B2A23800040F884 /* Project object */;

@ -34,8 +34,5 @@
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

@ -34,5 +34,4 @@
#import "AppDelegate.h"
@implementation AppDelegate
@end

@ -1,40 +0,0 @@
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end

@ -31,8 +31,10 @@
*
*/
#import "ViewController.h"
#import <UIKit/UIKit.h>
@implementation ViewController
@interface ViewController : UIViewController
@end
@implementation ViewController
@end

@ -2,15 +2,17 @@
## Installation
To run this example you 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).
To run this example you 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).
## Hello Objective-C gRPC!
Here's how to build and run the Objective-C implementation of the [Hello World](https://github.com/grpc/grpc-common/blob/master/protos/helloworld.proto) example used in [Getting started](https://github.com/grpc/grpc-common).
Here's how to build and run the Objective-C implementation of the [Hello World](https://github.com/grpc/grpc-common/blob/master/protos/helloworld.proto)
example used in [Getting started](https://github.com/grpc/grpc-common).
The example code for this and our other examples lives in the `grpc-common`
GitHub repository. Clone this repository to your local machine by running the
following command:
The example code for this and our other examples lives in the `grpc-common` GitHub repository. Clone
this repository to your local machine by running the following command:
```sh
@ -24,7 +26,8 @@ $ cd grpc-common/objective-c/helloworld
```
### Try it!
To try the sample app, we need a gRPC server running locally. Let's compile and run, for example, the C++ server in this repository:
To try the sample app, we need a gRPC server running locally. Let's compile and run, for example,
the C++ server in this repository:
```shell
$ pushd ../../cpp/helloworld
@ -39,12 +42,15 @@ Now have Cocoapods generate and install the client library for our .proto files:
$ pod install
```
This might have to compile OpenSSL, which takes around 15 minutes if Cocoapods doesn't have it yet on your computer's cache).
(This might have to compile OpenSSL, which takes around 15 minutes if Cocoapods doesn't have it yet
on your computer's cache.)
Finally, open the XCode workspace created by Cocoapods, and run the app. You can check the calling code in `main.m` and see the results in XCode's log console.
Finally, open the XCode workspace created by Cocoapods, and run the app. You can check the calling
code in `main.m` and see the results in XCode's log console.
The code sends a `HLWHelloRequest` containing the string "Objective-C" to a local server. The server responds with a `HLWHelloResponse`, which contains a string that is then output to the log.
The code sends a `HLWHelloRequest` containing the string "Objective-C" to a local server. The server
responds with a `HLWHelloResponse`, which contains a string that is then output to the log.
## Tutorial
You can find a more detailed tutorial in [gRPC Basics: Objective-C](https://github.com/grpc/grpc-common/blob/master/objective-c/route_guide/README.md)
You can find a more detailed tutorial in [gRPC Basics: Objective-C](https://github.com/grpc/grpc-common/blob/master/objective-c/route_guide/README.md).

@ -1,14 +1,20 @@
#gRPC Basics: Objective-C
This tutorial provides a basic Objective-C programmer's introduction to working with gRPC. By walking through this example you'll learn how to:
This tutorial provides a basic Objective-C programmer's introduction 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 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.
It 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.
This isn't a comprehensive guide to using gRPC in Objective-C: more reference documentation is coming soon.
This isn't a comprehensive guide to using gRPC in Objective-C: more reference documentation is
coming soon.
- [Why use gRPC?](#why-grpc)
- [Example code and setup](#setup)
@ -20,15 +26,25 @@ This isn't a comprehensive guide to using gRPC in Objective-C: more reference do
<a name="why-grpc"></a>
## Why use gRPC?
With 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.
With 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.
gRPC 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.
gRPC 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.
<a name="setup"></a>
## Example code and setup
The 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:
The 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:
```shell
$ git clone https://github.com/grpc/grpc-common.git
```
@ -38,15 +54,20 @@ Then change your current directory to `grpc-common/objective-c/route_guide`:
$ cd grpc-common/objective-c/route_guide
```
Our 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.
Our 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.
You 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).
You 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).
<a name="try"></a>
## Try it out!
To try the sample app, we need a gRPC server running locally. Let's compile and run, for example, the C++ server in this repository:
To try the sample app, we need a gRPC server running locally. Let's compile and run, for example,
the C++ server in this repository:
```shell
$ pushd ../../cpp/route_guide
@ -61,17 +82,22 @@ Now have Cocoapods generate and install the client library for our .proto files:
$ pod install
```
(This might have to compile OpenSSL, which takes around 15 minutes if Cocoapods doesn't have it yet on your computer's cache).
(This might have to compile OpenSSL, which takes around 15 minutes if Cocoapods doesn't have it yet
on your computer's cache).
Finally, 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.
Finally, 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.
The next sections guide you step-by-step through how this proto service is defined, how to generate a client library from it, and how to create an app that uses that library.
The next sections guide you step-by-step through how this proto service is defined, how to generate
a client library from it, and how to create an app that uses that library.
<a name="proto"></a>
## Defining the service
First let's look at how the service we're using is defined. A gRPC *service* and its method *request* and *response* types using [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file for our example in [`grpc-common/protos/route_guide.proto`](https://github.com/grpc/grpc-common/blob/master/protos/route_guide.proto).
First let's look at how the service we're using is defined. A gRPC *service* and its method
*request* and *response* types using [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview).
You can see the complete .proto file for our example in [`grpc-common/protos/route_guide.proto`](https://github.com/grpc/grpc-common/blob/master/protos/route_guide.proto).
To define a service, you specify a named `service` in your .proto file:
@ -81,15 +107,20 @@ service RouteGuide {
}
```
Then you define `rpc` methods inside your service definition, specifying their request and response types. Protocol buffers let you define four kinds of service method, all of which are used in the `RouteGuide` service:
Then you define `rpc` methods inside your service definition, specifying their request and response
types. Protocol buffers let you define four kinds of service method, all of which are used in the
`RouteGuide` service:
- A *simple RPC* where the client sends a request to the server and receives a response later, just like a normal remote procedure call.
- A *simple RPC* where the client sends a request to the server and receives a response later, just
like a normal remote procedure call.
```protobuf
// Obtains the feature at a given position.
rpc GetFeature(Point) returns (Feature) {}
```
- A *response-streaming RPC* where the client sends a request to the server and gets back a stream of response messages. You specify a response-streaming method by placing the `stream` keyword before the *response* type.
- A *response-streaming RPC* where the client sends a request to the server and gets back a stream
of response messages. You specify a response-streaming method by placing the `stream` keyword before
the *response* type.
```protobuf
// Obtains the Features available within the given Rectangle. Results are
// streamed rather than returned at once (e.g. in a response message with a
@ -98,21 +129,30 @@ Then you define `rpc` methods inside your service definition, specifying their r
rpc ListFeatures(Rectangle) returns (stream Feature) {}
```
- A *request-streaming RPC* where the client sends a sequence of messages to the server. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a request-streaming method by placing the `stream` keyword before the *request* type.
- A *request-streaming RPC* where the client sends a sequence of messages to the server. Once the
client has finished writing the messages, it waits for the server to read them all and return its
response. You specify a request-streaming method by placing the `stream` keyword before the
*request* type.
```protobuf
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
rpc RecordRoute(stream Point) returns (RouteSummary) {}
```
- A *bidirectional streaming RPC* where both sides send a sequence of messages to the other. 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.
- A *bidirectional streaming RPC* where both sides send a sequence of messages to the other. 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.
```protobuf
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
```
Our .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:
Our .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:
```protobuf
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
@ -124,7 +164,8 @@ message Point {
}
```
You can specify a prefix to be used for your generated classes by adding the `objc_class_prefix` option at the top of the file. For example:
You can specify a prefix to be used for your generated classes by adding the `objc_class_prefix`
option at the top of the file. For example:
```protobuf
option objc_class_prefix = "RTG";
```
@ -133,9 +174,12 @@ option objc_class_prefix = "RTG";
<a name="protoc"></a>
## Generating client code
Next 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.
Next 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.
For 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 (`grpc-common/objective-c/route_guide`):
For 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 (`grpc-common/objective-c/route_guide`):
```shell
$ pod install
@ -154,20 +198,28 @@ Running this command generates the following files under `Pods/RouteGuide/`:
- `RouteGuide.pbrpc.m`, which contains the implementation of your service classes.
These contain:
- All the protocol buffer code to populate, serialize, and retrieve our request and response message types.
- A class called `RTGRouteGuide` that lets clients call the methods defined in the `RouteGuide` service.
- All the protocol buffer code to populate, serialize, and retrieve our request and response message
types.
- A class called `RTGRouteGuide` that lets clients call the methods defined in the `RouteGuide`
service.
You can also use the provided Podspec file to generate client code from any other proto service definition; just replace the name (matching the file name), version, and other metadata.
You can also use the provided Podspec file to generate client code from any other proto service
definition; just replace the name (matching the file name), version, and other metadata.
<a name="client"></a>
## Creating the client
In 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).
In 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).
### Constructing a client object
To 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:
To 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:
```objective-c
#import <RouteGuide/RouteGuide.pbrpc.h>
@ -179,16 +231,24 @@ static NSString * const kHostAddress = @"http://localhost:50051";
RTGRouteGuide *client = [[RTGRouteGuide alloc] initWithHost:kHostAddress];
```
Notice 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). The default value of the port is that of the scheme selected: 443 for HTTPS and 80 for HTTP.
Notice 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). The default
value of the port is that of the scheme selected: 443 for HTTPS and 80 for HTTP.
### Calling service methods
Now 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.
Now 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.
#### Simple RPC
Calling the simple RPC `GetFeature` is nearly as straightforward as calling any other asynchronous method on Cocoa.
Calling the simple RPC `GetFeature` is nearly as straightforward as calling any other asynchronous
method on Cocoa.
```objective-c
RTGPoint *point = [RTGPoint message];
@ -204,7 +264,12 @@ point.longitude = -74E7;
}];
```
As 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 finishes 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 happens, the handler block is called with a `nil` response argument, and we can read the details of the problem from the error argument.
As 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 finishes 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 happens, the handler block is called with a `nil` response
argument, and we can read the details of the problem from the error argument.
```objective-c
NSLog(@"Found feature called %@ at %@.", response.name, response.location);
@ -212,10 +277,12 @@ NSLog(@"Found feature called %@ at %@.", response.name, response.location);
#### Streaming RPCs
Now 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:
Now 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:
```objective-c
[client listFeaturesWithRequest:rectangle handler:^(BOOL done, RTGFeature *response, NSError *error) {
[client listFeaturesWithRequest:rectangle
eventHandler:^(BOOL done, RTGFeature *response, NSError *error) {
if (response) {
// Element of the stream of responses received
} else if (error) {
@ -227,13 +294,18 @@ Now let's look at our streaming methods. Here's where we call the response-strea
}];
```
Notice how the signature of the handler block now includes a `BOOL done` parameter. The handler block can be called any number of times; only on the last call is the `done` argument value set to `YES`. If an error occurs, the RPC finishes and the handler is called with the arguments `(YES, nil, error)`.
Notice how the signature of the `eventHandler` block now includes a `BOOL done` parameter. The
`eventHandler` block can be called any number of times; only on the last call is the `done` argument
value set to `YES`. If an error occurs, the RPC finishes and the block is called with the arguments
`(YES, nil, error)`.
The 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:
The request-streaming method `RecordRoute` expects a stream of `RTGPoint`s from the cient. This
stream is passed to the method as an object of class `GRXWriter`. The simplest way to create one is
to initialize one from a `NSArray` object:
```objective-c
#import <gRPC/GRXWriter+Immediate.h>
#import <RxLibrary/GRXWriter+Immediate.h>
...
@ -247,7 +319,8 @@ point.longitude = -74E7;
GRXWriter *locationsWriter = [GRXWriter writerWithContainer:@[point1, point2]];
[client recordRouteWithRequestsWriter:locationsWriter handler:^(RTGRouteSummary *response, NSError *error) {
[client recordRouteWithRequestsWriter:locationsWriter
handler:^(RTGRouteSummary *response, NSError *error) {
if (response) {
NSLog(@"Finished trip with %i points", response.pointCount);
NSLog(@"Passed %i features", response.featureCount);
@ -260,12 +333,16 @@ GRXWriter *locationsWriter = [GRXWriter writerWithContainer:@[point1, point2]];
```
The `GRXWriter` protocol is generic enough to allow for asynchronous streams, streams of future values, or even infinite streams.
The `GRXWriter` class is generic enough to allow for asynchronous streams, streams of future values,
or even infinite streams.
Finally, 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.
Finally, 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.
```objective-c
[client routeChatWithRequestsWriter:notesWriter handler:^(BOOL done, RTGRouteNote *note, NSError *error) {
[client routeChatWithRequestsWriter:notesWriter
eventHandler:^(BOOL done, RTGRouteNote *note, NSError *error) {
if (note) {
NSLog(@"Got message %@ at %@", note.message, note.location);
} else if (error) {
@ -277,4 +354,7 @@ Finally, let's look at our bidirectional streaming RPC `RouteChat()`. The way to
}];
```
The 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.
The 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.

@ -29,7 +29,7 @@ Pod::Spec.new do |s|
ss.source_files = "#{dir}/*.pbrpc.{h,m}", "#{dir}/**/*.pbrpc.{h,m}"
ss.header_mappings_dir = dir
ss.requires_arc = true
ss.dependency "gRPC", "~> 0.5"
ss.dependency "gRPC", "~> 0.6"
ss.dependency "#{s.name}/Messages"
end
end

@ -32,9 +32,9 @@
*/
#import <UIKit/UIKit.h>
#import <gRPC/GRXWriter+Immediate.h>
#import <gRPC/GRXWriter+Transformations.h>
#import <RouteGuide/RouteGuide.pbrpc.h>
#import <RxLibrary/GRXWriter+Immediate.h>
#import <RxLibrary/GRXWriter+Transformations.h>
static NSString * const kHostAddress = @"http://localhost:50051";
@ -131,7 +131,8 @@ static NSString * const kHostAddress = @"http://localhost:50051";
rectangle.hi.longitude = -745E6;
NSLog(@"Looking for features between %@ and %@", rectangle.lo, rectangle.hi);
[client listFeaturesWithRequest:rectangle handler:^(BOOL done, RTGFeature *response, NSError *error) {
[client listFeaturesWithRequest:rectangle
eventHandler:^(BOOL done, RTGFeature *response, NSError *error) {
if (response) {
NSLog(@"Found feature at %@ called %@.", response.location, response.name);
} else if (error) {
@ -211,7 +212,8 @@ static NSString * const kHostAddress = @"http://localhost:50051";
RTGRouteGuide *client = [[RTGRouteGuide alloc] initWithHost:kHostAddress];
[client routeChatWithRequestsWriter:notesWriter handler:^(BOOL done, RTGRouteNote *note, NSError *error) {
[client routeChatWithRequestsWriter:notesWriter
eventHandler:^(BOOL done, RTGRouteNote *note, NSError *error) {
if (note) {
NSLog(@"Got message %@ at %@", note.message, note.location);
} else if (error) {

Loading…
Cancel
Save