SignInViewController.m 15 KB

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