FindPlaceLikelihoodListViewController.m 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. /*
  2. * Copyright 2019 Google LLC. All rights reserved.
  3. *
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
  6. * file except in compliance with the License. You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software distributed under
  11. * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  12. * ANY KIND, either express or implied. See the License for the specific language governing
  13. * permissions and limitations under the License.
  14. */
  15. #import "GooglePlacesDemos/Samples/FindPlaceLikelihoodListViewController.h"
  16. #import <GooglePlaces/GooglePlaces.h>
  17. static NSString *const kCellIdentifier = @"LikelihoodCellIdentifier";
  18. #pragma mark - ButtonCoordinateView
  19. @interface ButtonCoordinateView : UIView
  20. // The button used to trigger the fetch likelihoods from coordinate action.
  21. @property(nonatomic, strong) UIButton *button;
  22. @end
  23. @implementation ButtonCoordinateView {
  24. }
  25. - (instancetype)init {
  26. if (self = [super init]) {
  27. [self setupUI];
  28. }
  29. return self;
  30. }
  31. - (void)setupUI {
  32. self.layer.cornerRadius = 3;
  33. self.layer.masksToBounds = YES;
  34. self.layer.borderColor = [UIColor clearColor].CGColor;
  35. self.layer.borderWidth = 1;
  36. UIStackView *stackView = [[UIStackView alloc] init];
  37. stackView.axis = UILayoutConstraintAxisHorizontal;
  38. stackView.spacing = 15;
  39. stackView.layoutMargins = UIEdgeInsetsMake(5, 0, 5, 0);
  40. stackView.layoutMarginsRelativeArrangement = YES;
  41. [self addSubview:stackView];
  42. UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
  43. [button setTitle:@"Retrieve location" forState:UIControlStateNormal];
  44. [stackView addArrangedSubview:button];
  45. _button = button;
  46. UIStackView *labelsStackView = [[UIStackView alloc] init];
  47. labelsStackView.axis = UILayoutConstraintAxisVertical;
  48. [stackView addArrangedSubview:labelsStackView];
  49. [stackView setTranslatesAutoresizingMaskIntoConstraints:NO];
  50. [NSLayoutConstraint activateConstraints:@[
  51. [stackView.leadingAnchor constraintEqualToAnchor:self.leadingAnchor],
  52. [stackView.trailingAnchor constraintEqualToAnchor:self.trailingAnchor],
  53. [stackView.topAnchor constraintEqualToAnchor:self.topAnchor],
  54. [stackView.bottomAnchor constraintEqualToAnchor:self.bottomAnchor]
  55. ]];
  56. }
  57. // Sets the title and target for the button.
  58. - (void)fillWithButtonTitle:(NSString *)title
  59. target:(id)target
  60. action:(SEL)action
  61. forControlEvents:(UIControlEvents)controlEvents {
  62. [_button setTitle:title forState:UIControlStateNormal];
  63. [_button addTarget:target action:action forControlEvents:controlEvents];
  64. }
  65. @end
  66. #pragma mark - FindPlaceLikelihoodListViewController
  67. @interface FindPlaceLikelihoodListViewController ()
  68. @property(nonatomic, strong) UITableView *tableView;
  69. @property(nonatomic, strong) NSArray<GMSPlaceLikelihood *> *placeLikelihoods;
  70. @property(nonatomic, strong) UILabel *errorLabel;
  71. @property(nonatomic, strong) ButtonCoordinateView *currentButtonCoordinateView;
  72. @end
  73. @implementation FindPlaceLikelihoodListViewController {
  74. CLLocationManager *_locationManager;
  75. GMSPlacesClient *_placesClient;
  76. }
  77. + (NSString *)demoTitle {
  78. return @"Find Place Likelihoods";
  79. }
  80. - (void)viewDidLoad {
  81. [super viewDidLoad];
  82. _placesClient = [GMSPlacesClient sharedClient];
  83. // Initializes the location manager to be used for current location.
  84. CLLocationManager *locationManager = [[CLLocationManager alloc] init];
  85. locationManager.delegate = self;
  86. _locationManager = locationManager;
  87. self.title = [NSString stringWithFormat:@"Find place likelihoods from location"];
  88. #if defined(__IPHONE_13_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0)
  89. if (@available(iOS 13.0, *)) {
  90. self.view.backgroundColor = [UIColor systemBackgroundColor];
  91. } else {
  92. self.view.backgroundColor = [UIColor whiteColor];
  93. }
  94. #else
  95. self.view.backgroundColor = [UIColor whiteColor];
  96. #endif // defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
  97. UIStackView *mainStackView = [[UIStackView alloc] init];
  98. mainStackView.axis = UILayoutConstraintAxisVertical;
  99. [self.view addSubview:mainStackView];
  100. // Adds the location input section.
  101. UIStackView *locationInputStackView = [[UIStackView alloc] initWithFrame:CGRectZero];
  102. locationInputStackView.axis = UILayoutConstraintAxisVertical;
  103. locationInputStackView.layoutMargins = UIEdgeInsetsMake(20, 15, 0, 15);
  104. locationInputStackView.layoutMarginsRelativeArrangement = YES;
  105. locationInputStackView.distribution = UIStackViewDistributionFill;
  106. locationInputStackView.alignment = UIStackViewAlignmentFill;
  107. locationInputStackView.spacing = 10;
  108. [mainStackView addArrangedSubview:locationInputStackView];
  109. ButtonCoordinateView *currentView = [[ButtonCoordinateView alloc] init];
  110. [currentView fillWithButtonTitle:@"Find from current location"
  111. target:self
  112. action:@selector(onCurrentLocationTap)
  113. forControlEvents:UIControlEventTouchUpInside];
  114. [locationInputStackView addArrangedSubview:currentView];
  115. _currentButtonCoordinateView = currentView;
  116. UILabel *errorLabel = [[UILabel alloc] init];
  117. errorLabel.textColor = [UIColor redColor];
  118. errorLabel.numberOfLines = 0;
  119. [locationInputStackView addArrangedSubview:errorLabel];
  120. _errorLabel = errorLabel;
  121. // Adds the likelihood list table.
  122. UITableView *tableView = [[UITableView alloc] init];
  123. [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kCellIdentifier];
  124. tableView.delegate = self;
  125. tableView.dataSource = self;
  126. [mainStackView addArrangedSubview:tableView];
  127. _tableView = tableView;
  128. mainStackView.translatesAutoresizingMaskIntoConstraints = NO;
  129. NSArray<NSLayoutConstraint *> *stackViewConstraints = @[
  130. [mainStackView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
  131. [mainStackView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
  132. [mainStackView.topAnchor constraintEqualToAnchor:self.topLayoutGuide.bottomAnchor],
  133. [mainStackView.bottomAnchor constraintEqualToAnchor:self.bottomLayoutGuide.topAnchor]
  134. ];
  135. stackViewConstraints = @[
  136. [mainStackView.leadingAnchor
  137. constraintEqualToAnchor:self.view.safeAreaLayoutGuide.leadingAnchor],
  138. [mainStackView.trailingAnchor
  139. constraintEqualToAnchor:self.view.safeAreaLayoutGuide.trailingAnchor],
  140. [mainStackView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
  141. [mainStackView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor]
  142. ];
  143. [NSLayoutConstraint activateConstraints:stackViewConstraints];
  144. [self onCurrentLocationTap];
  145. }
  146. #pragma mark - Button Handlers
  147. // Requests location services authorization if needed, and starts updating location.
  148. - (void)onCurrentLocationTap {
  149. if (![FindPlaceLikelihoodListViewController areLocationServicesEnabledAndAuthorized]) {
  150. [_locationManager requestWhenInUseAuthorization];
  151. return;
  152. }
  153. [_locationManager startUpdatingLocation];
  154. __block FindPlaceLikelihoodListViewController *weakSelf = self;
  155. GMSPlaceLikelihoodsCallback fetcherCallback =
  156. ^(NSArray<GMSPlaceLikelihood *> *_Nullable likelihoods, NSError *_Nullable error) {
  157. [weakSelf handleFindPlaceLikelihoodsResponse:likelihoods error:error];
  158. };
  159. [_placesClient findPlaceLikelihoodsFromCurrentLocationWithPlaceFields:GMSPlaceFieldAll
  160. callback:fetcherCallback];
  161. }
  162. #pragma mark - CLLocationManagerDelegate
  163. // Retries retrieving current location if user has granted location services permission.
  164. - (void)locationManager:(CLLocationManager *)manager
  165. didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
  166. if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
  167. // Retry current location fetch once user enables Location Services.
  168. [self onCurrentLocationTap];
  169. } else {
  170. _errorLabel.text = @"Please make sure location services are enabled.";
  171. }
  172. }
  173. #pragma mark - UITableViewDataSource/Delegate
  174. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  175. if (_placeLikelihoods == nil) {
  176. return 0;
  177. }
  178. return _placeLikelihoods.count;
  179. }
  180. - (UITableViewCell *)tableView:(UITableView *)tableView
  181. cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  182. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier
  183. forIndexPath:indexPath];
  184. cell.textLabel.numberOfLines = 0;
  185. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  186. NSInteger row = indexPath.row;
  187. NSInteger likelihoodCount = _placeLikelihoods.count;
  188. if (likelihoodCount > 0 && row < likelihoodCount) {
  189. GMSPlaceLikelihood *likelihood = _placeLikelihoods[row];
  190. cell.textLabel.text = likelihood.place.name;
  191. }
  192. return cell;
  193. }
  194. #pragma mark - Helpers
  195. // Checks if user has authorized location services required for retrieving device location.
  196. + (BOOL)areLocationServicesEnabledAndAuthorized {
  197. if (![CLLocationManager locationServicesEnabled]) {
  198. return NO;
  199. }
  200. CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
  201. return status == kCLAuthorizationStatusAuthorizedAlways ||
  202. status == kCLAuthorizationStatusAuthorizedWhenInUse;
  203. }
  204. - (void)handleFindPlaceLikelihoodsResponse:(NSArray<GMSPlaceLikelihood *> *)likelihoods
  205. error:(NSError *)error {
  206. if (error != nil) {
  207. _errorLabel.text = @"There was an error fetching likelihoods.";
  208. return;
  209. }
  210. // Filters out Places that don't have a valid name.
  211. NSPredicate *predicate = [NSPredicate
  212. predicateWithBlock:^BOOL(GMSPlaceLikelihood *likelihood, NSDictionary<NSString *, id> *b) {
  213. return likelihood.place.name != nil && [likelihood.place.name length] > 0;
  214. }];
  215. _placeLikelihoods = [likelihoods filteredArrayUsingPredicate:predicate];
  216. _errorLabel.text = nil;
  217. [_tableView reloadData];
  218. [self resignFirstResponder];
  219. }
  220. @end