SignInViewController.m 14 KB

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