forked from eway2012/SampleCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForwardViewController.m
More file actions
623 lines (499 loc) · 20.4 KB
/
ForwardViewController.m
File metadata and controls
623 lines (499 loc) · 20.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
/*
File: ForwardViewController.m
Abstract: View controller in charge of forward geocoding.
Version: 1.2
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2012 Apple Inc. All Rights Reserved.
*/
#import "ForwardViewController.h"
#import "PlacemarksListViewController.h"
@interface ForwardViewController ()
@property (nonatomic, strong) CLLocationManager *locationManager; // location manager for current location
@property (nonatomic, strong) IBOutlet UITableViewCell *searchStringCell;
@property (nonatomic, strong) IBOutlet UITextField *searchStringTextField;
@property (nonatomic, strong) IBOutlet UISwitch *searchHintSwitch;
@property (nonatomic, strong) IBOutlet UITableViewCell *searchRadiusCell;
@property (nonatomic, strong) IBOutlet UILabel *searchRadiusLabel;
@property (nonatomic, strong) IBOutlet UISlider *searchRadiusSlider;
@property (readonly) CLLocationCoordinate2D selectedCoordinate;
@property (readonly) UIActivityIndicatorView *spinner; // weak
@property (readonly) UIActivityIndicatorView *currentLocationActivityIndicatorView; // weak
- (IBAction)hintSwitchChanged:(id)sender;
- (IBAction)radiusChanged:(id)sender;
@end
#pragma mark -
@implementation ForwardViewController
@synthesize searchStringCell = _searchStringCell;
@synthesize searchStringTextField = _searchStringTextField;
@synthesize searchHintSwitch = _searchHintSwitch;
@synthesize searchRadiusCell = _searchRadiusCell;
@synthesize searchRadiusLabel = _searchRadiusLabel;
@synthesize searchRadiusSlider = _searchRadiusSlider;
@synthesize selectedCoordinate = _selectedCoordinate;
@synthesize spinner = _spinner;
@synthesize currentLocationActivityIndicatorView = _currentLocationActivityIndicatorView;
@synthesize locationManager = _locationManager;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
self.title = @"Forward";
self.tabBarItem.image = [UIImage imageNamed:@"forward"];
}
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
_selectedCoordinate = kCLLocationCoordinate2DInvalid;
// load our custom table view cells from our nib
[[NSBundle mainBundle] loadNibNamed:@"ForwardViewControllerCells"
owner:self
options:nil];
#if 0
// forward geocode request using NSDictionary -
//
// geocodeAddressDictionary:completionHandler: takes an address dictionary as defined by the AddressBook framework.
// You can obtain an address dictionary from an ABPerson by retrieving the kABPersonAddressProperty property.
// Alternately, one can be constructed using the kABPersonAddress* keys defined in <AddressBook/ABPerson.h>.
//
NSDictionary *locationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"San Francisco", kABPersonAddressCityKey,
@"United States", kABPersonAddressCountryKey,
@"us", kABPersonAddressCountryCodeKey,
@"1398 Haight Street", kABPersonAddressStreetKey,
@"94117", kABPersonAddressZIPKey,
nil];
CLGeocoder *geocoder = [[[CLGeocoder alloc] init] autorelease];
[geocoder geocodeAddressDictionary:locationDictionary completionHandler:^(NSArray *placemarks, NSError *error)
{ }];
#endif
}
- (void)viewDidUnload
{
self.searchRadiusSlider = nil;
self.searchHintSwitch = nil;
self.searchRadiusCell = nil;
self.searchRadiusLabel = nil;
self.searchStringCell = nil;
self.searchStringTextField = nil;
// if the view has gone away, so should we set our weak pointer
_spinner = nil;
_currentLocationActivityIndicatorView = nil;
[super viewDidUnload];
}
- (void)dealloc
{
[_searchStringCell release];
[_searchStringTextField release];
[_searchHintSwitch release];
[_searchRadiusCell release];
[_searchRadiusLabel release];
[_searchRadiusSlider release];
_locationManager.delegate = nil;
[_locationManager release];
[super dealloc];
}
#pragma mark -
#pragma mark View Controller Appearance
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// return YES for supported orientations
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
else
{
return YES;
}
}
#pragma mark -
#pragma mark UI Handling
- (void)showSpinner:(UIActivityIndicatorView *)whichSpinner withShowState:(BOOL)show
{
whichSpinner.hidden = (show) ? NO : YES;
if (show)
{
[whichSpinner startAnimating];
}
else
{
[whichSpinner stopAnimating];
}
}
- (void)showCurrentLocationSpinner:(BOOL)show
{
if (!_currentLocationActivityIndicatorView)
{
// add the spinner to the table cell
UIActivityIndicatorView *curLocSpinner =
[[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
[curLocSpinner startAnimating];
[curLocSpinner setFrame:CGRectMake(200.0, 0.0, 22.0, 22.0)];
[curLocSpinner setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
assert(cell);
if (cell)
{
cell.accessoryView = curLocSpinner;
}
_currentLocationActivityIndicatorView = curLocSpinner; // keep a weak ref around for later
}
[self showSpinner:_currentLocationActivityIndicatorView withShowState:show];
}
- (void)showSpinner:(BOOL)show
{
if (!_spinner)
{
// add the spinner to the table's footer view
UIView* containerView = [[[UIView alloc] initWithFrame:
CGRectMake(0.0, 0.0, self.tableView.frame.size.width, 22.0)] autorelease];
UIActivityIndicatorView *spinner =
[[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
// size and center the spinner
[spinner setFrame:CGRectZero];
[spinner sizeToFit];
CGRect frame = spinner.frame;
frame.origin.x = (self.tableView.frame.size.width - frame.size.width) / 2.0;
spinner.frame = frame;
[spinner startAnimating];
[containerView addSubview:spinner];
self.tableView.tableFooterView = containerView;
_spinner = spinner; // keep a weak ref around for later
}
[self showSpinner:self.spinner withShowState:show];
}
- (void)lockUI
{
// prevent user interaction while we are processing the forward geocoding
self.tableView.allowsSelection = NO;
self.searchHintSwitch.enabled = NO;
self.searchRadiusSlider.enabled = NO;
[self showSpinner:YES];
}
- (void)unlockUI
{
// allow user interaction since we are done processing
self.tableView.allowsSelection = YES;
self.searchHintSwitch.enabled = YES;
self.searchRadiusSlider.enabled = YES;
[self showSpinner:NO];
}
#pragma mark -
#pragma mark Display Results
// display the results
- (void)displayPlacemarks:(NSArray *)placemarks
{
dispatch_async(dispatch_get_main_queue(),^ {
[self unlockUI];
PlacemarksListViewController *plvc = [[PlacemarksListViewController alloc] initWithPlacemarks:placemarks preferCoord:YES];
[self.navigationController pushViewController:plvc animated:YES];
[plvc release];
});
}
// display a given NSError in an UIAlertView
- (void)displayError:(NSError*)error
{
dispatch_async(dispatch_get_main_queue(),^ {
[self unlockUI];
NSString *message;
switch ([error code])
{
case kCLErrorGeocodeFoundNoResult:
message = @"kCLErrorGeocodeFoundNoResult";
break;
case kCLErrorGeocodeCanceled:
message = @"kCLErrorGeocodeCanceled";
break;
case kCLErrorGeocodeFoundPartialResult:
message = @"kCLErrorGeocodeFoundNoResult";
break;
default:
message = [error description];
break;
}
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"An error occurred."
message:message
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] autorelease];;
[alert show];
});
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// return the number of sections
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// return the number of rows in the section
if (section == 1)
return self.searchHintSwitch.on ? 3 : 1;
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// ----- interface builder generated cells -----
//
// search string cell
if (indexPath.section == 0)
{
return self.searchStringCell;
}
// search radius cell
if (indexPath.section == 1 && indexPath.row == 2)
{
return self.searchRadiusCell;
}
// ----- non interface builder generated cells -----
//
// search hint cell
if (indexPath.section == 1 && indexPath.row == 0)
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"radiusToggleCell"];
if (!cell)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"radiusToggleCell"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
_searchHintSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
[self.searchHintSwitch sizeToFit];
[self.searchHintSwitch addTarget:self action:@selector(hintSwitchChanged:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = self.searchHintSwitch;
cell.textLabel.text = @"Include Hint Region";
return cell;
}
// current location cell
if (indexPath.section == 1 && indexPath.row == 1)
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"radiusCell"];
if (!cell)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"radiusCell"] autorelease];
cell.textLabel.text = @"Current Location";
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied ||
[CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted )
{
cell.detailTextLabel.text = @"Location Services Disabled";
}
else
{
cell.detailTextLabel.text = @"<unknown>";
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
// basic cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"basicCell"];
if (!cell)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"basicCell"] autorelease];
// geocode button
if (indexPath.section == 2 && indexPath.row == 0)
{
cell.textLabel.text = @"Geocode String";
cell.textLabel.textAlignment = UITextAlignmentCenter;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
return cell;
}
#pragma mark - UITextFieldDelegate
// dismiss the keyboard for the textfields
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
// dismiss the keyboard upon a scroll
[self.searchStringTextField resignFirstResponder];
}
#pragma mark - CLLocationManagerDelegate
- (void)startUpdatingCurrentLocation
{
// if location services are restricted do nothing
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied ||
[CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted)
{
return;
}
// if locationManager does not currently exist, create it
if (!_locationManager)
{
_locationManager = [[CLLocationManager alloc] init];
[_locationManager setDelegate:self];
_locationManager.distanceFilter = 10.0f; // we don't need to be any more accurate than 10m
_locationManager.purpose = @"This will be used as part of the hint region for forward geocoding.";
}
[_locationManager startUpdatingLocation];
[self showCurrentLocationSpinner:YES];
}
- (void)stopUpdatingCurrentLocation
{
[_locationManager stopUpdatingLocation];
[self showCurrentLocationSpinner:NO];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// if the location is older than 30s ignore
if (fabs([newLocation.timestamp timeIntervalSinceDate:[NSDate date]]) > 30)
{
return;
}
_selectedCoordinate = [newLocation coordinate];
// update the current location cells detail label with these coords
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
cell.detailTextLabel.text = [NSString stringWithFormat:@"φ:%.4F, λ:%.4F", _selectedCoordinate.latitude, _selectedCoordinate.longitude];
// after recieving a location, stop updating
[self stopUpdatingCurrentLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"%@", error);
// stop updating
[self stopUpdatingCurrentLocation];
// since we got an error, set selected location to invalid location
_selectedCoordinate = kCLLocationCoordinate2DInvalid;
// show the error alert
UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
alert.title = @"Error obtaining location";
alert.message = [error localizedDescription];
[alert addButtonWithTitle:@"OK"];
[alert show];
}
#pragma mark -
#pragma mark Actions
- (IBAction)hintSwitchChanged:(id)sender
{
// show or hide the region hint cells
NSArray *indexes = [NSArray arrayWithObjects:
[NSIndexPath indexPathForRow:1 inSection:1],
[NSIndexPath indexPathForRow:2 inSection:1],
nil];
if (self.searchHintSwitch.on)
{
[self.tableView insertRowsAtIndexPaths:indexes withRowAnimation:UITableViewRowAnimationAutomatic];
// start searching for our location coordinates
[self startUpdatingCurrentLocation];
}
else
{
[self.tableView deleteRowsAtIndexPaths:indexes withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
- (IBAction)radiusChanged:(id)sender
{
self.searchRadiusLabel.text = [NSString stringWithFormat:@"%1.1f km", self.searchRadiusSlider.value/1000.0f];
}
- (IBAction)performStringGeocode:(id)sender
{
// dismiss the keyboard if it's currently open
if ([self.searchStringTextField isFirstResponder])
{
[self.searchStringTextField resignFirstResponder];
}
[self lockUI];
CLGeocoder *geocoder = [[[CLGeocoder alloc] init] autorelease];
// if we are going to includer region hint
if (self.searchHintSwitch.on)
{
// use hint region
CLLocationDistance dist = self.searchRadiusSlider.value; // 50,000m (50km)
CLLocationCoordinate2D point = _selectedCoordinate;
CLRegion *region = [[[CLRegion alloc] initCircularRegionWithCenter:point radius:dist identifier:@"Hint Region"] autorelease];
[geocoder geocodeAddressString:self.searchStringTextField.text inRegion:region completionHandler:^(NSArray *placemarks, NSError *error)
{
NSLog(@"geocodeAddressString:inRegion:completionHandler: Completion Handler called!");
if (error){
NSLog(@"Geocode failed with error: %@", error);
[self displayError:error];
return;
}
NSLog(@"Received placemarks: %@", placemarks);
[self displayPlacemarks:placemarks];
}];
}
else
{
// don't use a hint region
[geocoder geocodeAddressString:self.searchStringTextField.text completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(@"geocodeAddressString:completionHandler: Completion Handler called!");
if (error)
{
NSLog(@"Geocode failed with error: %@", error);
[self displayError:error];
return;
}
NSLog(@"Received placemarks: %@", placemarks);
[self displayPlacemarks:placemarks];
}];
}
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[[tableView cellForRowAtIndexPath:indexPath] setSelected:NO];
if (indexPath.section == 2 && indexPath.row == 0)
{
// perform the Geocode
[self performStringGeocode:self];
}
}
@end