DemoListViewController.m 17.2 KB
Newer Older
Julio Hermosa committed
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
/*
 * Copyright 2016 Google Inc. All rights reserved.
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

#import "GooglePlacesDemos/DemoListViewController.h"

#import <GooglePlaces/GooglePlaces.h>

// The cell reuse identifier we are going to use.
static NSString *const kCellIdentifier = @"DemoCellIdentifier";
static const CGFloat kSelectionHeight = 40;
static const CGFloat kSelectionSwitchWidth = 50;
static const CGFloat kEdgeBuffer = 8;

@implementation DemoListViewController {
  UIViewController *_editSelectionsViewController;
  NSMutableDictionary<NSNumber *, UISwitch *> *_autocompleteFiltersSelectionMap;
  NSMutableDictionary<NSNumber *, UISwitch *> *_placeFieldsSelectionMap;
  NSMutableDictionary<NSString *, UISwitch *> *_restrictionBoundsMap;
  CGFloat _nextSelectionYPos;
  DemoData *_demoData;
}

- (instancetype)initWithDemoData:(DemoData *)demoData {
  if ((self = [self init])) {
    _demoData = demoData;
    _autocompleteFiltersSelectionMap = [NSMutableDictionary dictionary];
    _placeFieldsSelectionMap = [NSMutableDictionary dictionary];
    _restrictionBoundsMap = [NSMutableDictionary dictionary];
  }
  return self;
}

- (void)viewWillAppear:(BOOL)animated {
  // Set up the title for view to be displayed.
  self.title = [DemoListViewController titleText];
  [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
  // Clear the title to make room for next view to share the header space in splitsreen view.
  self.title = nil;
  [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
  [super viewDidLoad];

  // Set up the edit selections UI.
  [self setUpEditSelectionsUI];

  // Add button to the header to edit the place field selections.
  self.navigationItem.rightBarButtonItem =
      [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit
                                                    target:self
                                                    action:@selector(beginEditSelections)];

  // Register a plain old UITableViewCell as this will be sufficient for our list.
  [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kCellIdentifier];

  //  [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(orientationChanged:)
                                               name:UIDeviceOrientationDidChangeNotification
                                             object:[UIDevice currentDevice]];
}

/**
 * Private method which is called when a demo is selected. Constructs the demo view controller and
 * displays it.
 *
 * @param demo The demo to show.
 */
- (void)showDemo:(Demo *)demo {
  CLLocationCoordinate2D northEast = kCLLocationCoordinate2DInvalid;
  CLLocationCoordinate2D southWest = kCLLocationCoordinate2DInvalid;
  GMSAutocompleteFilter *autocompleteFilter = [self autcompleteFilter];

  // Check for restriction bounds settings.
  if (_restrictionBoundsMap[@"Kansas"].on) {
    northEast = CLLocationCoordinate2DMake(39.0, -95.0);
    southWest = CLLocationCoordinate2DMake(37.5, -100.0);
    autocompleteFilter.origin = [[CLLocation alloc] initWithLatitude:northEast.latitude
                                                           longitude:northEast.longitude];
    autocompleteFilter.locationRestriction =
        GMSPlaceRectangularLocationOption(northEast, southWest);
  } else if (_restrictionBoundsMap[@"Canada"].on) {
    northEast = CLLocationCoordinate2DMake(70.0, -60.0);
    southWest = CLLocationCoordinate2DMake(50.0, -140.0);
    autocompleteFilter.origin = [[CLLocation alloc] initWithLatitude:northEast.latitude
                                                           longitude:northEast.longitude];
    autocompleteFilter.locationRestriction =
        GMSPlaceRectangularLocationOption(northEast, southWest);
  }

  // Create view controller with the autocomplete filters, bounds and selected place fields.
  UIViewController *viewController =
      [demo createViewControllerWithAutocompleteFilter:autocompleteFilter
                                           placeFields:[self selectedPlaceFields]];
  [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Edit Autocomplete Filters and Place Fields selections UI

- (void)setUpEditSelectionsUI {
  // Initialize the place fields selection UI.
  UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
  scrollView.backgroundColor = [UIColor whiteColor];

  // Add heading for the autocomplete type filters.
  _nextSelectionYPos = [UIApplication sharedApplication].statusBarFrame.size.height;
  [scrollView addSubview:[self headerLabelForTitle:@"Autcomplete Filters"]];

  // Set up the individual autocomplete type filters we can limit the results to.
  // Add a heading for the place fields that we can request.
  _nextSelectionYPos += kSelectionHeight;
  for (NSInteger autocompleteFilterType = kGMSPlacesAutocompleteTypeFilterGeocode;
       autocompleteFilterType <= kGMSPlacesAutocompleteTypeFilterCity; ++autocompleteFilterType) {
    [scrollView
        addSubview:[self selectionButtonForAutocompleteFilterType:(GMSPlacesAutocompleteTypeFilter)
                                                                      autocompleteFilterType]];
  }

  // Add heading for the autocomplete restriction bounds.
  [scrollView addSubview:[self headerLabelForTitle:@"Autcomplete Restriction Bounds"]];

  // Set up the restriction bounds for testing purposes.
  _nextSelectionYPos += kSelectionHeight;
  [scrollView addSubview:[self selectionButtonForRestrictionBoundsArea:@"Canada"]];

  _nextSelectionYPos += kSelectionHeight;
  [scrollView addSubview:[self selectionButtonForRestrictionBoundsArea:@"Kansas"]];

  // Add heading for the place fields that we can request.
  _nextSelectionYPos += kSelectionHeight;
  [scrollView addSubview:[self headerLabelForTitle:@"Place Fields"]];

  // Set up the individual place fields that we can request.
  _nextSelectionYPos += kSelectionHeight;
  for (NSUInteger placeField = GMSPlaceFieldName; placeField <= GMSPlaceFieldUTCOffsetMinutes;
       placeField <<= 1) {
    [scrollView addSubview:[self selectionButtonForPlaceField:(GMSPlaceField)placeField]];
  }

  // Add the close button to dismiss the selection UI.
  UIButton *close =
      [[UIButton alloc] initWithFrame:CGRectMake(0, _nextSelectionYPos, self.view.frame.size.width,
                                                 kSelectionHeight)];
  close.backgroundColor = [UIColor blueColor];
  [close setTitle:@"Close" forState:UIControlStateNormal];
  [close setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  [close addTarget:self
                action:@selector(endEditSelections:)
      forControlEvents:UIControlEventTouchUpInside];
  [scrollView addSubview:close];

  // Set the content size for the scroll view after we determine the height of all the contents.
  scrollView.contentSize = CGSizeMake(scrollView.frame.size.width,
                                      close.frame.origin.y + close.frame.size.height + kEdgeBuffer);

  // Initialize the edit selections view controller.
  _editSelectionsViewController = [[UIViewController alloc] init];
  _editSelectionsViewController.view = scrollView;
}

- (void)updateFrameForSelectionViews:(UIView *)view {
  CGFloat horizontalInset = [self horizontalInset];
  view.frame =
      CGRectMake(horizontalInset, view.frame.origin.y,
                 self.view.frame.size.width - (2 * horizontalInset), view.frame.size.height);
  for (UIView *subView in view.subviews) {
    if ([subView isKindOfClass:[UISwitch class]]) {
      subView.frame =
          CGRectMake(view.frame.size.width - kSelectionSwitchWidth, subView.frame.origin.y,
                     subView.frame.size.width, subView.frame.size.height);
    }
  }
}

- (UILabel *)headerLabelForTitle:(NSString *)title {
  UILabel *headerLabel =
      [[UILabel alloc] initWithFrame:CGRectMake(0, _nextSelectionYPos, self.view.frame.size.width,
                                                kSelectionHeight)];
  headerLabel.backgroundColor = [UIColor lightGrayColor];
  headerLabel.text = title;
  headerLabel.textAlignment = NSTextAlignmentCenter;
  headerLabel.textColor = [UIColor whiteColor];
  headerLabel.userInteractionEnabled = NO;
  return headerLabel;
}

- (UIButton *)selectionButtonForTitle:(NSString *)title {
  UIButton *selectionButton =
      [[UIButton alloc] initWithFrame:CGRectMake(0, _nextSelectionYPos, self.view.frame.size.width,
                                                 kSelectionHeight)];
  UISwitch *selectionSwitch = [[UISwitch alloc]
      initWithFrame:CGRectMake(selectionButton.frame.size.width - kSelectionSwitchWidth,
                               kEdgeBuffer / 2, kSelectionSwitchWidth, kSelectionHeight)];
  selectionSwitch.userInteractionEnabled = NO;
  [selectionButton addTarget:self
                      action:@selector(selectionButtonTapped:)
            forControlEvents:UIControlEventTouchUpInside];
  [selectionButton setBackgroundColor:[UIColor whiteColor]];
  [selectionButton setTitle:title forState:UIControlStateNormal];
  [selectionButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  selectionButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
  [selectionButton addSubview:selectionSwitch];
  return selectionButton;
}

- (UIButton *)selectionButtonForPlaceField:(GMSPlaceField)placeField {
  NSDictionary<NSNumber *, NSString *> *fieldsMapping = @{
    @(GMSPlaceFieldName) : @"Name",
    @(GMSPlaceFieldPlaceID) : @"Place ID",
    @(GMSPlaceFieldPlusCode) : @"Plus Code",
    @(GMSPlaceFieldCoordinate) : @"Coordinate",
    @(GMSPlaceFieldOpeningHours) : @"Opening Hours",
    @(GMSPlaceFieldPhoneNumber) : @"Phone Number",
    @(GMSPlaceFieldFormattedAddress) : @"Formatted Address",
    @(GMSPlaceFieldRating) : @"Rating",
    @(GMSPlaceFieldUserRatingsTotal) : @"User Ratings Total",
    @(GMSPlaceFieldPriceLevel) : @"Price Level",
    @(GMSPlaceFieldTypes) : @"Types",
    @(GMSPlaceFieldWebsite) : @"Website",
    @(GMSPlaceFieldViewport) : @"Viewport",
    @(GMSPlaceFieldAddressComponents) : @"Address Components",
    @(GMSPlaceFieldPhotos) : @"Photos",
    @(GMSPlaceFieldUTCOffsetMinutes) : @"UTC Offset Minutes",
  };
  UIButton *selectionButton = [self selectionButtonForTitle:fieldsMapping[@(placeField)]];
  UISwitch *selectionSwitch = [self switchFromButton:selectionButton];
  [selectionSwitch setOn:YES];
  _placeFieldsSelectionMap[@(placeField)] = selectionSwitch;
  _nextSelectionYPos += selectionButton.frame.size.height;
  return selectionButton;
}

- (UIButton *)selectionButtonForAutocompleteFilterType:
    (GMSPlacesAutocompleteTypeFilter)autocompleteFilter {
  NSDictionary<NSNumber *, NSString *> *fieldsMapping = @{
    @(kGMSPlacesAutocompleteTypeFilterGeocode) : @"Geocode",
    @(kGMSPlacesAutocompleteTypeFilterAddress) : @"Address",
    @(kGMSPlacesAutocompleteTypeFilterEstablishment) : @"Establishment",
    @(kGMSPlacesAutocompleteTypeFilterRegion) : @"Region",
    @(kGMSPlacesAutocompleteTypeFilterCity) : @"City",
  };
  UIButton *selectionButton = [self selectionButtonForTitle:fieldsMapping[@(autocompleteFilter)]];
  [selectionButton addTarget:self
                      action:@selector(disableOtherAutocompleteFilterExceptForTapped:)
            forControlEvents:UIControlEventTouchUpInside];
  UISwitch *selectionSwitch = [self switchFromButton:selectionButton];
  [selectionSwitch setOn:NO];
  _autocompleteFiltersSelectionMap[@(autocompleteFilter)] = selectionSwitch;
  _nextSelectionYPos += selectionButton.frame.size.height;
  return selectionButton;
}

- (UIButton *)selectionButtonForRestrictionBoundsArea:(NSString *)area {
  UIButton *selectionButton = [self selectionButtonForTitle:area];
  [selectionButton addTarget:self
                      action:@selector(disableOtherRestrictionBoundsExceptForTapped:)
            forControlEvents:UIControlEventTouchUpInside];
  _restrictionBoundsMap[area] = [self switchFromButton:selectionButton];
  [_restrictionBoundsMap[area] setOn:NO];
  return selectionButton;
}

- (UISwitch *)switchFromButton:(UIButton *)button {
  for (UIView *subView in button.subviews) {
    if ([subView isKindOfClass:[UISwitch class]]) {
      return (UISwitch *)subView;
    }
  }
  return nil;
}

- (void)selectionButtonTapped:(UIButton *)sender {
  UISwitch *selectionSwitch = [self switchFromButton:sender];
  [selectionSwitch setOn:selectionSwitch.on ? NO : YES animated:YES];
}

- (void)disableOtherAutocompleteFilterExceptForTapped:(UIButton *)sender {
  UISwitch *tappedSwitch = [self switchFromButton:sender];
  for (NSNumber *number in _autocompleteFiltersSelectionMap) {
    UISwitch *selectionSwitch = _autocompleteFiltersSelectionMap[number];
    if (selectionSwitch != tappedSwitch) {
      [selectionSwitch setOn:NO animated:YES];
    }
  }
}

- (void)disableOtherRestrictionBoundsExceptForTapped:(UIButton *)sender {
  UISwitch *tappedSwitch = [self switchFromButton:sender];
  for (NSString *key in [_restrictionBoundsMap allKeys]) {
    UISwitch *selectionSwitch = _restrictionBoundsMap[key];
    if (selectionSwitch != tappedSwitch) {
      [selectionSwitch setOn:NO animated:YES];
    }
  }
}

- (void)beginEditSelections {
  // Update the selection views to fit the current device frame and orientation.
  for (UIView *view in _editSelectionsViewController.view.subviews) {
    [self updateFrameForSelectionViews:view];
  }

  // Scroll the contents to the top before presenting the selection UI.
  UIScrollView *scrollView = (UIScrollView *)_editSelectionsViewController.view;
  [scrollView setContentOffset:CGPointZero animated:NO];

  // Present the selection UI to edit which place fields to request.
  [self.navigationController presentViewController:_editSelectionsViewController
                                          animated:YES
                                        completion:nil];
}

- (void)endEditSelections:(UIButton *)sender {
  [_editSelectionsViewController dismissViewControllerAnimated:YES completion:nil];
}

- (GMSAutocompleteFilter *)autcompleteFilter {
  GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
  for (NSNumber *number in _autocompleteFiltersSelectionMap) {
    UISwitch *selectionSwitch = _autocompleteFiltersSelectionMap[number];
    if ([selectionSwitch isOn]) {
      filter.type = (GMSPlacesAutocompleteTypeFilter)[number integerValue];
      break;
    }
  }
  return filter;
}

- (GMSPlaceField)selectedPlaceFields {
  GMSPlaceField placeFields = 0;
  for (NSNumber *number in _placeFieldsSelectionMap) {
    UISwitch *selectionSwitch = _placeFieldsSelectionMap[number];
    if ([selectionSwitch isOn]) {
      placeFields |= [number integerValue];
    }
  }
  return placeFields;
}

- (CGFloat)horizontalInset {
#if defined(__IPHONE_11_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0)
  // Take into account the safe areas of the device screen and do not use that space.
  if (@available(iOS 11.0, *)) {
    return MAX(self.view.safeAreaInsets.left, self.view.safeAreaInsets.right) + kEdgeBuffer;
  }
#endif
  return kEdgeBuffer;
}

#pragma mark - UITableViewDataSource/Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return _demoData.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return _demoData.sections[section].demos.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  // Dequeue a table view cell to use.
  UITableViewCell *cell =
      [tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];

  // Grab the demo object.
  Demo *demo = _demoData.sections[indexPath.section].demos[indexPath.row];

  // Configure the demo title on the cell.
  cell.textLabel.text = demo.title;

  return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  return _demoData.sections[section].title;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  // Get the demo which was selected.
  Demo *demo = _demoData.sections[indexPath.section].demos[indexPath.row];
  [self showDemo:demo];
}

+ (NSString *)titleText {
  NSString *titleFormat = NSLocalizedString(
      @"App.NameAndVersion", @"The name of the app to display in a navigation bar along with a "
                             @"placeholder for the SDK version number");
  return [NSString stringWithFormat:titleFormat, [GMSPlacesClient SDKLongVersion]];
}

#pragma mark - Handle Orientation Changes

- (void)orientationChanged:(NSNotification *)notification {
  // Dismiss the selections UI if currently active.
  if (_editSelectionsViewController.isViewLoaded && _editSelectionsViewController.view.window) {
    [self endEditSelections:nil];
  }
}

@end