SignInViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /*
  2. * Copyright 2021 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * 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
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "SignInViewController.h"
  17. @import GoogleSignIn;
  18. #import "AuthInspectorViewController.h"
  19. #import "DataPickerState.h"
  20. #import "DataPickerViewController.h"
  21. static NSString *const kSignInViewTitle = @"Sign-In Sample";
  22. static NSString *const kPlaceholderUserName = @"<Name>";
  23. static NSString *const kPlaceholderEmailAddress = @"<Email>";
  24. static NSString *const kPlaceholderAvatarImageName = @"PlaceholderAvatar.png";
  25. // Labels for the cells that have in-cell control elements.
  26. static NSString *const kButtonWidthCellLabel = @"Width";
  27. // Labels for the cells that drill down to data pickers.
  28. static NSString *const kColorSchemeCellLabel = @"Color scheme";
  29. static NSString *const kStyleCellLabel = @"Style";
  30. // Accessibility Identifiers.
  31. static NSString *const kCredentialsButtonAccessibilityIdentifier = @"Credentials";
  32. // DO NOT USE THIS CLIENT ID. IT WILL NOT WORK FOR YOUR APP.
  33. // Please use the client ID created for you by Google.
  34. static NSString * const kClientID =
  35. @"589453917038-qaoga89fitj2ukrsq27ko56fimmojac6.apps.googleusercontent.com";
  36. @implementation SignInViewController {
  37. // This is an array of arrays, each one corresponding to the cell
  38. // labels for its respective section.
  39. NSArray *_sectionCellLabels;
  40. // These sets contain the labels corresponding to cells that have various types (each cell either
  41. // drills down to another table view or contains a slider).
  42. NSArray *_drillDownCells;
  43. NSArray *_sliderCells;
  44. // States storing the current set of selected elements for each data picker.
  45. DataPickerState *_colorSchemeState;
  46. DataPickerState *_styleState;
  47. // Map that keeps track of which cell corresponds to which DataPickerState.
  48. NSDictionary *_drilldownCellState;
  49. // Configuration options for GIDSignIn.
  50. GIDConfiguration *_configuration;
  51. }
  52. #pragma mark - View lifecycle
  53. - (void)setUp {
  54. _sectionCellLabels = @[
  55. @[ kColorSchemeCellLabel, kStyleCellLabel, kButtonWidthCellLabel ]
  56. ];
  57. // Groupings of cell types.
  58. _drillDownCells = @[
  59. kColorSchemeCellLabel,
  60. kStyleCellLabel
  61. ];
  62. _sliderCells = @[ kButtonWidthCellLabel ];
  63. // Initialize data picker states.
  64. NSString *dictionaryPath =
  65. [[NSBundle mainBundle] pathForResource:@"DataPickerDictionary"
  66. ofType:@"plist"];
  67. NSDictionary *configOptionsDict = [NSDictionary dictionaryWithContentsOfFile:dictionaryPath];
  68. NSDictionary *colorSchemeDict = [configOptionsDict objectForKey:kColorSchemeCellLabel];
  69. NSDictionary *styleDict = [configOptionsDict objectForKey:kStyleCellLabel];
  70. _colorSchemeState = [[DataPickerState alloc] initWithDictionary:colorSchemeDict];
  71. _styleState = [[DataPickerState alloc] initWithDictionary:styleDict];
  72. _drilldownCellState = @{
  73. kColorSchemeCellLabel : _colorSchemeState,
  74. kStyleCellLabel : _styleState
  75. };
  76. // Make sure the GIDSignInButton class is linked in because references from
  77. // xib file doesn't count.
  78. [GIDSignInButton class];
  79. _configuration = [[GIDConfiguration alloc] initWithClientID:kClientID];
  80. }
  81. - (id)initWithNibName:(NSString *)nibNameOrNil
  82. bundle:(NSBundle *)nibBundleOrNil {
  83. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  84. if (self) {
  85. [self setUp];
  86. self.title = kSignInViewTitle;
  87. }
  88. return self;
  89. }
  90. - (id)initWithCoder:(NSCoder *)aDecoder {
  91. self = [super initWithCoder:aDecoder];
  92. if (self) {
  93. [self setUp];
  94. self.title = kSignInViewTitle;
  95. }
  96. return self;
  97. }
  98. - (void)viewDidLoad {
  99. [super viewDidLoad];
  100. self.credentialsButton.accessibilityIdentifier = kCredentialsButtonAccessibilityIdentifier;
  101. }
  102. - (void)viewWillAppear:(BOOL)animated {
  103. [self adoptUserSettings];
  104. [self reportAuthStatus];
  105. [self updateButtons];
  106. [self.tableView reloadData];
  107. [super viewWillAppear:animated];
  108. }
  109. - (IBAction)signInPressed:(id)sender {
  110. [GIDSignIn.sharedInstance signInWithConfiguration:_configuration
  111. presentingViewController:self
  112. callback:^(GIDGoogleUser * _Nullable user,
  113. NSError * _Nullable error) {
  114. if (error) {
  115. self->_signInAuthStatus.text =
  116. [NSString stringWithFormat:@"Status: Authentication error: %@", error];
  117. return;
  118. }
  119. [self reportAuthStatus];
  120. [self updateButtons];
  121. }];
  122. }
  123. #pragma mark - Helper methods
  124. // Updates the GIDSignIn shared instance and the GIDSignInButton
  125. // to reflect the configuration settings that the user set
  126. - (void)adoptUserSettings {
  127. // There should only be one selected color scheme
  128. for (NSString *scheme in _colorSchemeState.selectedCells) {
  129. if ([scheme isEqualToString:@"Light"]) {
  130. _signInButton.colorScheme = kGIDSignInButtonColorSchemeLight;
  131. } else {
  132. _signInButton.colorScheme = kGIDSignInButtonColorSchemeDark;
  133. }
  134. }
  135. // There should only be one selected style
  136. for (NSString *style in _styleState.selectedCells) {
  137. GIDSignInButtonStyle newStyle;
  138. if ([style isEqualToString:@"Standard"]) {
  139. newStyle = kGIDSignInButtonStyleStandard;
  140. self.signInButtonWidthSlider.enabled = YES;
  141. } else if ([style isEqualToString:@"Wide"]) {
  142. newStyle = kGIDSignInButtonStyleWide;
  143. self.signInButtonWidthSlider.enabled = YES;
  144. } else {
  145. newStyle = kGIDSignInButtonStyleIconOnly;
  146. self.signInButtonWidthSlider.enabled = NO;
  147. }
  148. if (self.signInButton.style != newStyle) {
  149. self.signInButton.style = newStyle;
  150. self.signInButtonWidthSlider.minimumValue = [self minimumButtonWidth];
  151. }
  152. self.signInButtonWidthSlider.value = _signInButton.frame.size.width;
  153. }
  154. }
  155. // Temporarily force the sign in button to adopt its minimum allowed frame
  156. // so that we can find out its minimum allowed width (used for setting the
  157. // range of the width slider).
  158. - (CGFloat)minimumButtonWidth {
  159. CGRect frame = self.signInButton.frame;
  160. self.signInButton.frame = CGRectZero;
  161. CGFloat minimumWidth = self.signInButton.frame.size.width;
  162. self.signInButton.frame = frame;
  163. return minimumWidth;
  164. }
  165. - (void)reportAuthStatus {
  166. GIDGoogleUser *googleUser = [GIDSignIn.sharedInstance currentUser];
  167. if (googleUser.authentication) {
  168. _signInAuthStatus.text = @"Status: Authenticated";
  169. } else {
  170. // To authenticate, use Google Sign-In button.
  171. _signInAuthStatus.text = @"Status: Not authenticated";
  172. }
  173. [self refreshUserInfo];
  174. }
  175. // Update the interface elements containing user data to reflect the
  176. // currently signed in user.
  177. - (void)refreshUserInfo {
  178. if (GIDSignIn.sharedInstance.currentUser.authentication == nil) {
  179. self.userName.text = kPlaceholderUserName;
  180. self.userEmailAddress.text = kPlaceholderEmailAddress;
  181. self.userAvatar.image = [UIImage imageNamed:kPlaceholderAvatarImageName];
  182. return;
  183. }
  184. self.userEmailAddress.text = GIDSignIn.sharedInstance.currentUser.profile.email;
  185. self.userName.text = GIDSignIn.sharedInstance.currentUser.profile.name;
  186. if (!GIDSignIn.sharedInstance.currentUser.profile.hasImage) {
  187. // There is no Profile Image to be loaded.
  188. return;
  189. }
  190. // Load avatar image asynchronously, in background
  191. dispatch_queue_t backgroundQueue =
  192. dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  193. __weak SignInViewController *weakSelf = self;
  194. NSUInteger dimension = round(self.userAvatar.frame.size.width * [[UIScreen mainScreen] scale]);
  195. NSURL *imageURL =
  196. [GIDSignIn.sharedInstance.currentUser.profile imageURLWithDimension:dimension];
  197. dispatch_async(backgroundQueue, ^{
  198. NSData *avatarData = [NSData dataWithContentsOfURL:imageURL];
  199. if (avatarData) {
  200. // Update UI from the main thread when available
  201. dispatch_async(dispatch_get_main_queue(), ^{
  202. SignInViewController *strongSelf = weakSelf;
  203. if (strongSelf) {
  204. strongSelf.userAvatar.image = [UIImage imageWithData:avatarData];
  205. }
  206. });
  207. }
  208. });
  209. }
  210. // Adjusts "Sign in", "Sign out", and "Disconnect" buttons to reflect
  211. // the current sign-in state (ie, the "Sign in" button becomes disabled
  212. // when a user is already signed in).
  213. - (void)updateButtons {
  214. BOOL authenticated = (GIDSignIn.sharedInstance.currentUser.authentication != nil);
  215. self.signInButton.enabled = !authenticated;
  216. self.signOutButton.enabled = authenticated;
  217. self.disconnectButton.enabled = authenticated;
  218. self.credentialsButton.hidden = !authenticated;
  219. if (authenticated) {
  220. self.signInButton.alpha = 0.5;
  221. self.signOutButton.alpha = self.disconnectButton.alpha = 1.0;
  222. } else {
  223. self.signInButton.alpha = 1.0;
  224. self.signOutButton.alpha = self.disconnectButton.alpha = 0.5;
  225. }
  226. }
  227. #pragma mark - IBActions
  228. - (IBAction)signOut:(id)sender {
  229. [GIDSignIn.sharedInstance signOut];
  230. [self reportAuthStatus];
  231. [self updateButtons];
  232. }
  233. - (IBAction)disconnect:(id)sender {
  234. [GIDSignIn.sharedInstance disconnectWithCallback:^(NSError * _Nullable error) {
  235. if (error) {
  236. self->_signInAuthStatus.text = [NSString stringWithFormat:@"Status: Failed to disconnect: %@",
  237. error];
  238. } else {
  239. self->_signInAuthStatus.text = [NSString stringWithFormat:@"Status: Disconnected"];
  240. }
  241. [self reportAuthStatus];
  242. [self updateButtons];
  243. }];
  244. }
  245. - (IBAction)showAuthInspector:(id)sender {
  246. AuthInspectorViewController *authInspector = [[AuthInspectorViewController alloc] init];
  247. [[self navigationController] pushViewController:authInspector animated:YES];
  248. }
  249. - (IBAction)checkSignIn:(id)sender {
  250. [self reportAuthStatus];
  251. }
  252. - (void)changeSignInButtonWidth:(UISlider *)sender {
  253. CGRect frame = self.signInButton.frame;
  254. frame.size.width = sender.value;
  255. self.signInButton.frame = frame;
  256. }
  257. #pragma mark - UITableView Data Source
  258. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  259. return [_sectionCellLabels count];
  260. }
  261. - (NSInteger)tableView:(UITableView *)tableView
  262. numberOfRowsInSection:(NSInteger)section {
  263. return [_sectionCellLabels[section] count];
  264. }
  265. - (NSString *)tableView:(UITableView *)tableView
  266. titleForHeaderInSection:(NSInteger)section {
  267. if (section == 0) {
  268. return @"Sign-In Button Options";
  269. } else if (section == 1) {
  270. return @"Other Options";
  271. } else {
  272. return nil;
  273. }
  274. }
  275. - (BOOL)tableView:(UITableView *)tableView
  276. shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
  277. // Cells that drill down to other table views should be highlight-able.
  278. // The other cells contain control elements, so they should not be selectable.
  279. NSString *label = _sectionCellLabels[indexPath.section][indexPath.row];
  280. if ([_drillDownCells containsObject:label]) {
  281. return YES;
  282. } else {
  283. return NO;
  284. }
  285. }
  286. - (UITableViewCell *)tableView:(UITableView *)tableView
  287. cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  288. static NSString * const kDrilldownCell = @"DrilldownCell";
  289. static NSString * const kSliderCell = @"SliderCell";
  290. NSString *label = _sectionCellLabels[indexPath.section][indexPath.row];
  291. UITableViewCell *cell;
  292. NSString *identifier;
  293. if ([_drillDownCells containsObject:label]) {
  294. identifier = kDrilldownCell;
  295. } else if ([_sliderCells containsObject:label]) {
  296. identifier = kSliderCell;
  297. }
  298. cell = [tableView dequeueReusableCellWithIdentifier:identifier];
  299. if (cell == nil) {
  300. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
  301. reuseIdentifier:identifier];
  302. }
  303. // Assign accessibility labels to each cell row.
  304. cell.accessibilityLabel = label;
  305. if (identifier == kDrilldownCell) {
  306. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  307. DataPickerState *dataState = _drilldownCellState[label];
  308. if (dataState.multipleSelectEnabled) {
  309. cell.detailTextLabel.text = @"";
  310. } else {
  311. cell.detailTextLabel.text = [dataState.selectedCells anyObject];
  312. }
  313. cell.accessibilityValue = cell.detailTextLabel.text;
  314. } else if (identifier == kSliderCell) {
  315. UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, 150, 0)];
  316. slider.minimumValue = [self minimumButtonWidth];
  317. slider.maximumValue = 268.0;
  318. slider.value = self.signInButton.frame.size.width;
  319. slider.enabled = self.signInButton.style != kGIDSignInButtonStyleIconOnly;
  320. [slider addTarget:self
  321. action:@selector(changeSignInButtonWidth:)
  322. forControlEvents:UIControlEventValueChanged];
  323. slider.accessibilityIdentifier = [NSString stringWithFormat:@"%@ Slider", label];
  324. self.signInButtonWidthSlider = slider;
  325. cell.accessoryView = slider;
  326. [self.signInButtonWidthSlider sizeToFit];
  327. }
  328. cell.textLabel.text = label;
  329. return cell;
  330. }
  331. - (void)tableView:(UITableView *)tableView
  332. didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  333. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  334. UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
  335. NSString *label = selectedCell.textLabel.text;
  336. DataPickerState *dataState = [_drilldownCellState objectForKey:label];
  337. if (!dataState) {
  338. return;
  339. }
  340. DataPickerViewController *dataPicker =
  341. [[DataPickerViewController alloc] initWithNibName:nil
  342. bundle:nil
  343. dataState:dataState];
  344. dataPicker.navigationItem.title = label;
  345. // Force the back button title to be 'Back'
  346. UIBarButtonItem *newBackButton =
  347. [[UIBarButtonItem alloc] initWithTitle:@"Back"
  348. style:UIBarButtonItemStylePlain
  349. target:nil
  350. action:nil];
  351. [[self navigationItem] setBackBarButtonItem:newBackButton];
  352. [self.navigationController pushViewController:dataPicker animated:YES];
  353. }
  354. @end