Imported Upstream version 1.21.0
[platform/upstream/grpc.git] / examples / objective-c / route_guide / ViewControllers.m
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 #import <UIKit/UIKit.h>
20 #import <RouteGuide/RouteGuide.pbrpc.h>
21
22 static NSString * const kHostAddress = @"localhost:50051";
23
24 /** Category to override RTGPoint's description. */
25 @interface RTGPoint (Description)
26 - (NSString *)description;
27 @end
28
29 @implementation RTGPoint (Description)
30 - (NSString *)description {
31   NSString *verticalDirection = self.latitude >= 0 ? @"N" : @"S";
32   NSString *horizontalDirection = self.longitude >= 0 ? @"E" : @"W";
33   return [NSString stringWithFormat:@"%.02f%@ %.02f%@",
34           abs(self.latitude) / 1E7f, verticalDirection,
35           abs(self.longitude) / 1E7f, horizontalDirection];
36 }
37 @end
38
39 /** Category to give RTGRouteNote a convenience constructor. */
40 @interface RTGRouteNote (Constructors)
41 + (instancetype)noteWithMessage:(NSString *)message
42                        latitude:(float)latitude
43                       longitude:(float)longitude;
44 @end
45
46 @implementation RTGRouteNote (Constructors)
47 + (instancetype)noteWithMessage:(NSString *)message
48                        latitude:(float)latitude
49                       longitude:(float)longitude {
50   RTGRouteNote *note = [self message];
51   note.message = message;
52   note.location.latitude = (int32_t) latitude * 1E7;
53   note.location.longitude = (int32_t) longitude * 1E7;
54   return note;
55 }
56 @end
57
58
59 #pragma mark Demo: Get Feature
60
61 /**
62  * Run the getFeature demo. Calls getFeature with a point known to have a feature and a point known
63  * not to have a feature.
64  */
65 @interface GetFeatureViewController : UIViewController<GRPCProtoResponseHandler>
66
67 @property (weak, nonatomic) IBOutlet UILabel *outputLabel;
68
69 @end
70
71 @implementation GetFeatureViewController {
72   RTGRouteGuide *_service;
73 }
74
75 - (dispatch_queue_t)dispatchQueue {
76   return dispatch_get_main_queue();
77 }
78
79 - (void)didReceiveProtoMessage:(GPBMessage *)message {
80   RTGFeature *response = (RTGFeature *)message;
81
82   // TODO(makdharma): Remove boilerplate by consolidating into one log function.
83   if (response.name.length != 0) {
84     NSString *str =[NSString stringWithFormat:@"%@\nFound feature called %@ at %@.", self.outputLabel.text, response.location, response.name];
85     self.outputLabel.text = str;
86     NSLog(@"Found feature called %@ at %@.", response.name, response.location);
87   } else if (response) {
88     NSString *str =[NSString stringWithFormat:@"%@\nFound no features at %@",  self.outputLabel.text,response.location];
89     self.outputLabel.text = str;
90     NSLog(@"Found no features at %@", response.location);
91   }
92 }
93
94 - (void)didCloseWithTrailingMetadata:(NSDictionary *)trailingMetadata error:(NSError *)error {
95   if (error) {
96     NSString *str =[NSString stringWithFormat:@"%@\nRPC error: %@", self.outputLabel.text, error];
97     self.outputLabel.text = str;
98     NSLog(@"RPC error: %@", error);
99   }
100 }
101
102 - (void)execRequest {
103   RTGPoint *point = [RTGPoint message];
104   point.latitude = 409146138;
105   point.longitude = -746188906;
106
107   GRPCUnaryProtoCall *call = [_service getFeatureWithMessage:point
108                                              responseHandler:self
109                                                  callOptions:nil];
110   [call start];
111   call = [_service getFeatureWithMessage:[RTGPoint message]
112                          responseHandler:self
113                              callOptions:nil];
114   [call start];
115
116 }
117
118 - (void)viewDidLoad {
119   [super viewDidLoad];
120
121   GRPCMutableCallOptions *options = [[GRPCMutableCallOptions alloc] init];
122   options.transportType = GRPCTransportTypeInsecure;
123
124   _service = [[RTGRouteGuide alloc] initWithHost:kHostAddress callOptions:options];
125 }
126
127 - (void)viewDidAppear:(BOOL)animated {
128   self.outputLabel.text = @"RPC log:";
129   self.outputLabel.numberOfLines = 0;
130   self.outputLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:8.0];
131   [self execRequest];
132 }
133
134 @end
135
136
137 #pragma mark Demo: List Features
138
139 /**
140  * Run the listFeatures demo. Calls listFeatures with a rectangle containing all of the features in
141  * the pre-generated database. Prints each response as it comes in.
142  */
143 @interface ListFeaturesViewController : UIViewController<GRPCProtoResponseHandler>
144
145 @property (weak, nonatomic) IBOutlet UILabel *outputLabel;
146
147 @end
148
149 @implementation ListFeaturesViewController {
150   RTGRouteGuide *_service;
151 }
152
153 - (dispatch_queue_t)dispatchQueue {
154   return dispatch_get_main_queue();
155 }
156
157 - (void)execRequest {
158   RTGRectangle *rectangle = [RTGRectangle message];
159   rectangle.lo.latitude = 405E6;
160   rectangle.lo.longitude = -750E6;
161   rectangle.hi.latitude = 410E6;
162   rectangle.hi.longitude = -745E6;
163
164   NSLog(@"Looking for features between %@ and %@", rectangle.lo, rectangle.hi);
165   GRPCUnaryProtoCall *call = [_service listFeaturesWithMessage:rectangle
166                                                responseHandler:self
167                                                    callOptions:nil];
168   [call start];
169 }
170
171 - (void)didReceiveProtoMessage:(GPBMessage *)message {
172   RTGFeature *response = (RTGFeature *)message;
173   if (response) {
174     NSString *str =[NSString stringWithFormat:@"%@\nFound feature at %@ called %@.", self.outputLabel.text, response.location, response.name];
175     self.outputLabel.text = str;
176     NSLog(@"Found feature at %@ called %@.", response.location, response.name);
177   }
178 }
179
180 - (void)didCloseWithTrailingMetadata:(NSDictionary *)trailingMetadata error:(NSError *)error {
181   if (error) {
182     NSString *str =[NSString stringWithFormat:@"%@\nRPC error: %@", self.outputLabel.text, error];
183     self.outputLabel.text = str;
184     NSLog(@"RPC error: %@", error);
185   }
186 }
187
188 - (void)viewDidLoad {
189   [super viewDidLoad];
190
191   GRPCMutableCallOptions *options = [[GRPCMutableCallOptions alloc] init];
192   options.transportType = GRPCTransportTypeInsecure;
193
194   _service = [[RTGRouteGuide alloc] initWithHost:kHostAddress callOptions:options];
195 }
196
197 - (void)viewDidAppear:(BOOL)animated {
198   self.outputLabel.text = @"RPC log:";
199   self.outputLabel.numberOfLines = 0;
200   self.outputLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:8.0];
201   [self execRequest];
202 }
203
204 @end
205
206 #pragma mark Demo: Record Route
207
208 /**
209  * Run the recordRoute demo. Sends several randomly chosen points from the pre-generated feature
210  * database with a variable delay in between. Prints the statistics when they are sent from the
211  * server.
212  */
213 @interface RecordRouteViewController : UIViewController<GRPCProtoResponseHandler>
214
215 @property (weak, nonatomic) IBOutlet UILabel *outputLabel;
216
217 @end
218
219 @implementation RecordRouteViewController {
220   RTGRouteGuide *_service;
221 }
222
223 - (dispatch_queue_t)dispatchQueue {
224   return dispatch_get_main_queue();
225 }
226
227 - (void)execRequest {
228   NSString *dataBasePath = [NSBundle.mainBundle pathForResource:@"route_guide_db"
229                                                          ofType:@"json"];
230   NSData *dataBaseContent = [NSData dataWithContentsOfFile:dataBasePath];
231   NSError *error;
232   NSArray *features = [NSJSONSerialization JSONObjectWithData:dataBaseContent options:0 error:&error];
233
234   if (error) {
235     NSLog(@"Error reading database.");
236     NSString *str = @"Error reading database.";
237     self.outputLabel.text = str;
238     return;
239   }
240
241   GRPCStreamingProtoCall *call = [_service recordRouteWithResponseHandler:self
242                                                               callOptions:nil];
243   [call start];
244   for (id feature in features) {
245     RTGPoint *location = [RTGPoint message];
246     location.longitude = [((NSNumber *) feature[@"location"][@"longitude"]) intValue];
247     location.latitude = [((NSNumber *) feature[@"location"][@"latitude"]) intValue];
248     NSString *str =[NSString stringWithFormat:@"%@\nVisiting point %@", self.outputLabel.text, location];
249     self.outputLabel.text = str;
250     NSLog(@"Visiting point %@", location);
251     [call writeMessage:location];
252   }
253   [call finish];
254 }
255
256 - (void)didReceiveProtoMessage:(GPBMessage *)message {
257   RTGRouteSummary *response = (RTGRouteSummary *)message;
258
259   if (response) {
260     NSString *str =[NSString stringWithFormat:
261                     @"%@\nFinished trip with %i points\nPassed %i features\n"
262                     "Travelled %i meters\nIt took %i seconds",
263                     self.outputLabel.text, response.pointCount, response.featureCount,
264                     response.distance, response.elapsedTime];
265     self.outputLabel.text = str;
266     NSLog(@"Finished trip with %i points", response.pointCount);
267     NSLog(@"Passed %i features", response.featureCount);
268     NSLog(@"Travelled %i meters", response.distance);
269     NSLog(@"It took %i seconds", response.elapsedTime);
270   }
271 }
272
273 - (void)didCloseWithTrailingMetadata:(NSDictionary *)trailingMetadata error:(NSError *)error {
274   if (error) {
275     NSString *str =[NSString stringWithFormat:@"%@\nRPC error: %@", self.outputLabel.text, error];
276     self.outputLabel.text = str;
277     NSLog(@"RPC error: %@", error);
278   }
279 }
280
281 - (void)viewDidLoad {
282   [super viewDidLoad];
283
284   GRPCMutableCallOptions *options = [[GRPCMutableCallOptions alloc] init];
285   options.transportType = GRPCTransportTypeInsecure;
286
287   _service = [[RTGRouteGuide alloc] initWithHost:kHostAddress callOptions:options];
288 }
289
290 - (void)viewDidAppear:(BOOL)animated {
291   self.outputLabel.text = @"RPC log:";
292   self.outputLabel.numberOfLines = 0;
293   self.outputLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:8.0];
294   [self execRequest];
295 }
296
297 @end
298
299
300 #pragma mark Demo: Route Chat
301
302 /**
303  * Run the routeChat demo. Send some chat messages, and print any chat messages that are sent from
304  * the server.
305  */
306 @interface RouteChatViewController : UIViewController<GRPCProtoResponseHandler>
307
308 @property (weak, nonatomic) IBOutlet UILabel *outputLabel;
309
310 @end
311
312 @implementation RouteChatViewController {
313   RTGRouteGuide *_service;
314 }
315
316 - (dispatch_queue_t)dispatchQueue {
317   return dispatch_get_main_queue();
318 }
319
320 - (void)execRequest {
321   NSArray *notes = @[[RTGRouteNote noteWithMessage:@"First message" latitude:0 longitude:0],
322                      [RTGRouteNote noteWithMessage:@"Second message" latitude:0 longitude:1],
323                      [RTGRouteNote noteWithMessage:@"Third message" latitude:1 longitude:0],
324                      [RTGRouteNote noteWithMessage:@"Fourth message" latitude:0 longitude:0]];
325
326   GRPCStreamingProtoCall *call = [_service routeChatWithResponseHandler:self
327                                                             callOptions:nil];
328   [call start];
329   for (RTGRouteNote *note in notes) {
330     [call writeMessage:note];
331   }
332   [call finish];
333 }
334
335 - (void)didReceiveProtoMessage:(GPBMessage *)message {
336   RTGRouteNote *note = (RTGRouteNote *)message;
337   if (note) {
338     NSString *str =[NSString stringWithFormat:@"%@\nGot message %@ at %@",
339                     self.outputLabel.text, note.message, note.location];
340     self.outputLabel.text = str;
341     NSLog(@"Got message %@ at %@", note.message, note.location);
342   }
343 }
344
345 - (void)didCloseWithTrailingMetadata:(NSDictionary *)trailingMetadata error:(NSError *)error {
346   if (!error) {
347     NSLog(@"Chat ended.");
348   } else {
349     NSString *str =[NSString stringWithFormat:@"%@\nRPC error: %@", self.outputLabel.text, error];
350     self.outputLabel.text = str;
351     NSLog(@"RPC error: %@", error);
352   }
353 }
354
355 - (void)viewDidLoad {
356   [super viewDidLoad];
357
358   GRPCMutableCallOptions *options = [[GRPCMutableCallOptions alloc] init];
359   options.transportType = GRPCTransportTypeInsecure;
360
361   _service = [[RTGRouteGuide alloc] initWithHost:kHostAddress callOptions:options];
362 }
363
364 - (void)viewDidAppear:(BOOL)animated {
365   // TODO(makarandd): Set these properties through UI builder
366   self.outputLabel.text = @"RPC log:";
367   self.outputLabel.numberOfLines = 0;
368   self.outputLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:8.0];
369   [self execRequest];
370 }
371
372 @end