SignInViewController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. #pragma mark - Helper methods
  110. // Updates the GIDSignIn shared instance and the GIDSignInButton
  111. // to reflect the configuration settings that the user set
  112. - (void)adoptUserSettings {
  113. // There should only be one selected color scheme
  114. for (NSString *scheme in _colorSchemeState.selectedCells) {
  115. if ([scheme isEqualToString:@"Light"]) {
  116. _signInButton.colorScheme = kGIDSignInButtonColorSchemeLight;
  117. } else {
  118. _signInButton.colorScheme = kGIDSignInButtonColorSchemeDark;
  119. }
  120. }
  121. // There should only be one selected style
  122. for (NSString *style in _styleState.selectedCells) {
  123. GIDSignInButtonStyle newStyle;
  124. if ([style isEqualToString:@"Standard"]) {
  125. newStyle = kGIDSignInButtonStyleStandard;
  126. self.signInButtonWidthSlider.enabled = YES;
  127. } else if ([style isEqualToString:@"Wide"]) {
  128. newStyle = kGIDSignInButtonStyleWide;
  129. self.signInButtonWidthSlider.enabled = YES;
  130. } else {
  131. newStyle = kGIDSignInButtonStyleIconOnly;
  132. self.signInButtonWidthSlider.enabled = NO;
  133. }
  134. if (self.signInButton.style != newStyle) {
  135. self.signInButton.style = newStyle;
  136. self.signInButtonWidthSlider.minimumValue = [self minimumButtonWidth];
  137. }
  138. self.signInButtonWidthSlider.value = _signInButton.frame.size.width;
  139. }
  140. }
  141. // Temporarily force the sign in button to adopt its minimum allowed frame
  142. // so that we can find out its minimum allowed width (used for setting the
  143. // range of the width slider).
  144. - (CGFloat)minimumButtonWidth {
  145. CGRect frame = self.signInButton.frame;
  146. self.signInButton.frame = CGRectZero;
  147. CGFloat minimumWidth = self.signInButton.frame.size.width;
  148. self.signInButton.frame = frame;
  149. return minimumWidth;
  150. }
  151. - (void)reportAuthStatus {
  152. GIDGoogleUser *googleUser = [GIDSignIn.sharedInstance currentUser];
  153. if (googleUser.authentication) {
  154. _signInAuthStatus.text = @"Status: Authenticated";
  155. } else {
  156. // To authenticate, use Google Sign-In button.
  157. _signInAuthStatus.text = @"Status: Not authenticated";
  158. }
  159. [self refreshUserInfo];
  160. }
  161. // Update the interface elements containing user data to reflect the
  162. // currently signed in user.
  163. - (void)refreshUserInfo {
  164. if (GIDSignIn.sharedInstance.currentUser.authentication == nil) {
  165. self.userName.text = kPlaceholderUserName;
  166. self.userEmailAddress.text = kPlaceholderEmailAddress;
  167. self.userAvatar.image = [UIImage imageNamed:kPlaceholderAvatarImageName];
  168. return;
  169. }
  170. self.userEmailAddress.text = GIDSignIn.sharedInstance.currentUser.profile.email;
  171. self.userName.text = GIDSignIn.sharedInstance.currentUser.profile.name;
  172. if (!GIDSignIn.sharedInstance.currentUser.profile.hasImage) {
  173. // There is no Profile Image to be loaded.
  174. return;
  175. }
  176. // Load avatar image asynchronously, in background
  177. dispatch_queue_t backgroundQueue =
  178. dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  179. __weak SignInViewController *weakSelf = self;
  180. NSUInteger dimension = round(self.userAvatar.frame.size.width * [[UIScreen mainScreen] scale]);
  181. NSURL *imageURL =
  182. [GIDSignIn.sharedInstance.currentUser.profile imageURLWithDimension:dimension];
  183. dispatch_async(backgroundQueue, ^{
  184. NSData *avatarData = [NSData dataWithContentsOfURL:imageURL];
  185. if (avatarData) {
  186. // Update UI from the main thread when available
  187. dispatch_async(dispatch_get_main_queue(), ^{
  188. SignInViewController *strongSelf = weakSelf;
  189. if (strongSelf) {
  190. strongSelf.userAvatar.image = [UIImage imageWithData:avatarData];
  191. }
  192. });
  193. }
  194. });
  195. }
  196. // Adjusts "Sign in", "Sign out", "Disconnect", and "Add Scopes" buttons to reflect the current
  197. // sign-in state (ie, the "Sign in" button becomes disabled when a user is already signed in).
  198. - (void)updateButtons {
  199. BOOL hasCurrentUser = (GIDSignIn.sharedInstance.currentUser != nil);
  200. self.signInButton.enabled = !hasCurrentUser;
  201. self.signOutButton.enabled = hasCurrentUser;
  202. self.disconnectButton.enabled = hasCurrentUser;
  203. self.addScopesButton.enabled = hasCurrentUser;
  204. self.credentialsButton.hidden = !hasCurrentUser;
  205. if (hasCurrentUser) {
  206. self.signInButton.alpha = 0.5;
  207. self.signOutButton.alpha = self.disconnectButton.alpha = self.addScopesButton.alpha = 1.0;
  208. } else {
  209. self.signInButton.alpha = 1.0;
  210. self.signOutButton.alpha = self.disconnectButton.alpha = self.addScopesButton.alpha = 0.5;
  211. }
  212. }
  213. #pragma mark - IBActions
  214. - (IBAction)signIn:(id)sender {
  215. [GIDSignIn.sharedInstance signInWithConfiguration:_configuration
  216. presentingViewController:self
  217. callback:^(GIDGoogleUser * _Nullable user,
  218. NSError * _Nullable error) {
  219. if (error) {
  220. self->_signInAuthStatus.text =
  221. [NSString stringWithFormat:@"Status: Authentication error: %@", error];
  222. return;
  223. }
  224. [self reportAuthStatus];
  225. [self updateButtons];
  226. }];
  227. }
  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)addScopes:(id)sender {
  246. [GIDSignIn.sharedInstance addScopes:@[ @"https://www.googleapis.com/auth/user.birthday.read" ]
  247. presentingViewController:self
  248. callback:^(GIDGoogleUser * _Nullable user,
  249. NSError * _Nullable error) {
  250. if (error) {
  251. self->_signInAuthStatus.text = [NSString stringWithFormat:@"Status: Failed to add scopes: %@",
  252. error];
  253. } else {
  254. self->_signInAuthStatus.text = [NSString stringWithFormat:@"Status: Scopes added"];
  255. }
  256. [self refreshUserInfo];
  257. }];
  258. }
  259. - (IBAction)showAuthInspector:(id)sender {
  260. AuthInspectorViewController *authInspector = [[AuthInspectorViewController alloc] init];
  261. [[self navigationController] pushViewController:authInspector animated:YES];
  262. }
  263. - (IBAction)checkSignIn:(id)sender {
  264. [self reportAuthStatus];
  265. }
  266. - (void)changeSignInButtonWidth:(UISlider *)sender {
  267. CGRect frame = self.signInButton.frame;
  268. frame.size.width = sender.value;
  269. self.signInButton.frame = frame;
  270. }
  271. #pragma mark - UITableView Data Source
  272. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  273. return [_sectionCellLabels count];
  274. }
  275. - (NSInteger)tableView:(UITableView *)tableView
  276. numberOfRowsInSection:(NSInteger)section {
  277. return [_sectionCellLabels[section] count];
  278. }
  279. - (NSString *)tableView:(UITableView *)tableView
  280. titleForHeaderInSection:(NSInteger)section {
  281. if (section == 0) {
  282. return @"Sign-In Button Options";
  283. } else if (section == 1) {
  284. return @"Other Options";
  285. } else {
  286. return nil;
  287. }
  288. }
  289. - (BOOL)tableView:(UITableView *)tableView
  290. shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
  291. // Cells that drill down to other table views should be highlight-able.
  292. // The other cells contain control elements, so they should not be selectable.
  293. NSString *label = _sectionCellLabels[indexPath.section][indexPath.row];
  294. if ([_drillDownCells containsObject:label]) {
  295. return YES;
  296. } else {
  297. return NO;
  298. }
  299. }
  300. - (UITableViewCell *)tableView:(UITableView *)tableView
  301. cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  302. static NSString * const kDrilldownCell = @"DrilldownCell";
  303. static NSString * const kSliderCell = @"SliderCell";
  304. NSString *label = _sectionCellLabels[indexPath.section][indexPath.row];
  305. UITableViewCell *cell;
  306. NSString *identifier;
  307. if ([_drillDownCells containsObject:label]) {
  308. identifier = kDrilldownCell;
  309. } else if ([_sliderCells containsObject:label]) {
  310. identifier = kSliderCell;
  311. }
  312. cell = [tableView dequeueReusableCellWithIdentifier:identifier];
  313. if (cell == nil) {
  314. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
  315. reuseIdentifier:identifier];
  316. }
  317. // Assign accessibility labels to each cell row.
  318. cell.accessibilityLabel = label;
  319. if (identifier == kDrilldownCell) {
  320. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  321. DataPickerState *dataState = _drilldownCellState[label];
  322. if (dataState.multipleSelectEnabled) {
  323. cell.detailTextLabel.text = @"";
  324. } else {
  325. cell.detailTextLabel.text = [dataState.selectedCells anyObject];
  326. }
  327. cell.accessibilityValue = cell.detailTextLabel.text;
  328. } else if (identifier == kSliderCell) {
  329. UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, 150, 0)];
  330. slider.minimumValue = [self minimumButtonWidth];
  331. slider.maximumValue = 268.0;
  332. slider.value = self.signInButton.frame.size.width;
  333. slider.enabled = self.signInButton.style != kGIDSignInButtonStyleIconOnly;
  334. [slider addTarget:self
  335. action:@selector(changeSignInButtonWidth:)
  336. forControlEvents:UIControlEventValueChanged];
  337. slider.accessibilityIdentifier = [NSString stringWithFormat:@"%@ Slider", label];
  338. self.signInButtonWidthSlider = slider;
  339. cell.accessoryView = slider;
  340. [self.signInButtonWidthSlider sizeToFit];
  341. }
  342. cell.textLabel.text = label;
  343. return cell;
  344. }
  345. - (void)tableView:(UITableView *)tableView
  346. didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  347. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  348. UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
  349. NSString *label = selectedCell.textLabel.text;
  350. DataPickerState *dataState = [_drilldownCellState objectForKey:label];
  351. if (!dataState) {
  352. return;
  353. }
  354. DataPickerViewController *dataPicker =
  355. [[DataPickerViewController alloc] initWithNibName:nil
  356. bundle:nil
  357. dataState:dataState];
  358. dataPicker.navigationItem.title = label;
  359. // Force the back button title to be 'Back'
  360. UIBarButtonItem *newBackButton =
  361. [[UIBarButtonItem alloc] initWithTitle:@"Back"
  362. style:UIBarButtonItemStylePlain
  363. target:nil
  364. action:nil];
  365. [[self navigationItem] setBackBarButtonItem:newBackButton];
  366. [self.navigationController pushViewController:dataPicker animated:YES];
  367. }
  368. @end