SignInViewController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. completion:^(GIDGoogleUser *user, NSError *error) {
  218. if (error) {
  219. self->_signInAuthStatus.text =
  220. [NSString stringWithFormat:@"Status: Authentication error: %@", error];
  221. return;
  222. }
  223. [self reportAuthStatus];
  224. [self updateButtons];
  225. }];
  226. }
  227. - (IBAction)signOut:(id)sender {
  228. [GIDSignIn.sharedInstance signOut];
  229. [self reportAuthStatus];
  230. [self updateButtons];
  231. }
  232. - (IBAction)disconnect:(id)sender {
  233. [GIDSignIn.sharedInstance disconnectWithCompletion:^(NSError *error) {
  234. if (error) {
  235. self->_signInAuthStatus.text = [NSString stringWithFormat:@"Status: Failed to disconnect: %@",
  236. error];
  237. } else {
  238. self->_signInAuthStatus.text = [NSString stringWithFormat:@"Status: Disconnected"];
  239. }
  240. [self reportAuthStatus];
  241. [self updateButtons];
  242. }];
  243. }
  244. - (IBAction)addScopes:(id)sender {
  245. [GIDSignIn.sharedInstance addScopes:@[ @"https://www.googleapis.com/auth/user.birthday.read" ]
  246. presentingViewController:self
  247. completion:^(GIDGoogleUser *user, NSError *error) {
  248. if (error) {
  249. self->_signInAuthStatus.text = [NSString stringWithFormat:@"Status: Failed to add scopes: %@",
  250. error];
  251. } else {
  252. self->_signInAuthStatus.text = [NSString stringWithFormat:@"Status: Scopes added"];
  253. }
  254. [self refreshUserInfo];
  255. }];
  256. }
  257. - (IBAction)showAuthInspector:(id)sender {
  258. AuthInspectorViewController *authInspector = [[AuthInspectorViewController alloc] init];
  259. [[self navigationController] pushViewController:authInspector animated:YES];
  260. }
  261. - (IBAction)checkSignIn:(id)sender {
  262. [self reportAuthStatus];
  263. }
  264. - (void)changeSignInButtonWidth:(UISlider *)sender {
  265. CGRect frame = self.signInButton.frame;
  266. frame.size.width = sender.value;
  267. self.signInButton.frame = frame;
  268. }
  269. #pragma mark - UITableView Data Source
  270. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  271. return [_sectionCellLabels count];
  272. }
  273. - (NSInteger)tableView:(UITableView *)tableView
  274. numberOfRowsInSection:(NSInteger)section {
  275. return [_sectionCellLabels[section] count];
  276. }
  277. - (NSString *)tableView:(UITableView *)tableView
  278. titleForHeaderInSection:(NSInteger)section {
  279. if (section == 0) {
  280. return @"Sign-In Button Options";
  281. } else if (section == 1) {
  282. return @"Other Options";
  283. } else {
  284. return nil;
  285. }
  286. }
  287. - (BOOL)tableView:(UITableView *)tableView
  288. shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
  289. // Cells that drill down to other table views should be highlight-able.
  290. // The other cells contain control elements, so they should not be selectable.
  291. NSString *label = _sectionCellLabels[indexPath.section][indexPath.row];
  292. if ([_drillDownCells containsObject:label]) {
  293. return YES;
  294. } else {
  295. return NO;
  296. }
  297. }
  298. - (UITableViewCell *)tableView:(UITableView *)tableView
  299. cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  300. static NSString * const kDrilldownCell = @"DrilldownCell";
  301. static NSString * const kSliderCell = @"SliderCell";
  302. NSString *label = _sectionCellLabels[indexPath.section][indexPath.row];
  303. UITableViewCell *cell;
  304. NSString *identifier;
  305. if ([_drillDownCells containsObject:label]) {
  306. identifier = kDrilldownCell;
  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 == kSliderCell) {
  327. UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, 150, 0)];
  328. slider.minimumValue = [self minimumButtonWidth];
  329. slider.maximumValue = 268.0;
  330. slider.value = self.signInButton.frame.size.width;
  331. slider.enabled = self.signInButton.style != kGIDSignInButtonStyleIconOnly;
  332. [slider addTarget:self
  333. action:@selector(changeSignInButtonWidth:)
  334. forControlEvents:UIControlEventValueChanged];
  335. slider.accessibilityIdentifier = [NSString stringWithFormat:@"%@ Slider", label];
  336. self.signInButtonWidthSlider = slider;
  337. cell.accessoryView = slider;
  338. [self.signInButtonWidthSlider sizeToFit];
  339. }
  340. cell.textLabel.text = label;
  341. return cell;
  342. }
  343. - (void)tableView:(UITableView *)tableView
  344. didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  345. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  346. UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
  347. NSString *label = selectedCell.textLabel.text;
  348. DataPickerState *dataState = [_drilldownCellState objectForKey:label];
  349. if (!dataState) {
  350. return;
  351. }
  352. DataPickerViewController *dataPicker =
  353. [[DataPickerViewController alloc] initWithNibName:nil
  354. bundle:nil
  355. dataState:dataState];
  356. dataPicker.navigationItem.title = label;
  357. // Force the back button title to be 'Back'
  358. UIBarButtonItem *newBackButton =
  359. [[UIBarButtonItem alloc] initWithTitle:@"Back"
  360. style:UIBarButtonItemStylePlain
  361. target:nil
  362. action:nil];
  363. [[self navigationItem] setBackBarButtonItem:newBackButton];
  364. [self.navigationController pushViewController:dataPicker animated:YES];
  365. }
  366. @end