UIViewController+Alerts.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /*
  2. * Copyright 2019 Google
  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 "UIViewController+Alerts.h"
  17. #import <objc/runtime.h>
  18. /*! @var kPleaseWaitAssociatedObjectKey
  19. @brief Key used to identify the "please wait" spinner associated object.
  20. */
  21. static NSString *const kPleaseWaitAssociatedObjectKey =
  22. @"_UIViewControllerAlertCategory_PleaseWaitScreenAssociatedObject";
  23. /*! @var kUseStatusBarSpinnerAssociatedObjectKey
  24. @brief The address of this constant is the key used to identify the "use status bar spinner"
  25. associated object.
  26. */
  27. static const void *const kUseStatusBarSpinnerAssociatedObjectKey;
  28. /*! @var kOK
  29. @brief Text for an 'OK' button.
  30. */
  31. static NSString *const kOK = @"OK";
  32. /*! @var kCancel
  33. @brief Text for an 'Cancel' button.
  34. */
  35. static NSString *const kCancel = @"Cancel";
  36. /*! @class SimpleTextPromptDelegate
  37. @brief A @c UIAlertViewDelegate which allows @c UIAlertView to be used with blocks more easily.
  38. */
  39. @interface SimpleTextPromptDelegate : NSObject <UIAlertViewDelegate>
  40. /*! @fn init
  41. @brief Please use initWithCompletionHandler.
  42. */
  43. - (nullable instancetype)init NS_UNAVAILABLE;
  44. /*! @fn initWithCompletionHandler:
  45. @brief Designated initializer.
  46. @param completionHandler The block to call when the alert view is dismissed.
  47. */
  48. - (nullable instancetype)initWithCompletionHandler:(AlertPromptCompletionBlock)completionHandler
  49. NS_DESIGNATED_INITIALIZER;
  50. @end
  51. @implementation UIViewController (Alerts)
  52. - (void)setUseStatusBarSpinner:(BOOL)useStatusBarSpinner {
  53. objc_setAssociatedObject(self,
  54. &kUseStatusBarSpinnerAssociatedObjectKey,
  55. useStatusBarSpinner ? @(YES) : nil,
  56. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  57. }
  58. - (BOOL)useStatusBarSpinner {
  59. return objc_getAssociatedObject(self, &kUseStatusBarSpinnerAssociatedObjectKey) ? YES : NO;
  60. }
  61. /*! @fn supportsAlertController
  62. @brief Determines if the current platform supports @c UIAlertController.
  63. @return YES if the current platform supports @c UIAlertController.
  64. */
  65. - (BOOL)supportsAlertController {
  66. return NSClassFromString(@"UIAlertController") != nil;
  67. }
  68. - (void)showMessagePrompt:(NSString *)message {
  69. [self showMessagePromptWithTitle:nil message:message showCancelButton:NO completion:nil];
  70. }
  71. - (void)showMessagePromptWithTitle:(nullable NSString *)title
  72. message:(NSString *)message
  73. showCancelButton:(BOOL)showCancelButton
  74. completion:(nullable AlertPromptCompletionBlock)completion {
  75. if (message) {
  76. [UIPasteboard generalPasteboard].string = message;
  77. }
  78. if ([self supportsAlertController]) {
  79. UIAlertController *alert =
  80. [UIAlertController alertControllerWithTitle:title
  81. message:message
  82. preferredStyle:UIAlertControllerStyleAlert];
  83. UIAlertAction *okAction =
  84. [UIAlertAction actionWithTitle:kOK
  85. style:UIAlertActionStyleDefault
  86. handler:^(UIAlertAction * _Nonnull action) {
  87. if (completion) {
  88. completion(YES, nil);
  89. }
  90. }];
  91. [alert addAction:okAction];
  92. if (showCancelButton) {
  93. UIAlertAction *cancelAction =
  94. [UIAlertAction actionWithTitle:kCancel
  95. style:UIAlertActionStyleCancel
  96. handler:^(UIAlertAction * _Nonnull action) {
  97. completion(NO, nil);
  98. }];
  99. [alert addAction:cancelAction];
  100. }
  101. [self presentViewController:alert animated:YES completion:nil];
  102. } else {
  103. UIAlertController* alert = [UIAlertController alertControllerWithTitle:title
  104. message:message
  105. preferredStyle:UIAlertControllerStyleAlert];
  106. [self presentViewController:alert animated:YES completion:nil];
  107. }
  108. }
  109. - (void)showTextInputPromptWithMessage:(NSString *)message
  110. completionBlock:(AlertPromptCompletionBlock)completion {
  111. [self showTextInputPromptWithMessage:message
  112. keyboardType:UIKeyboardTypeDefault
  113. completionBlock:completion];
  114. }
  115. - (void)showTextInputPromptWithMessage:(NSString *)message
  116. keyboardType:(UIKeyboardType)keyboardType
  117. completionBlock:(nonnull AlertPromptCompletionBlock)completion {
  118. if ([self supportsAlertController]) {
  119. UIAlertController *prompt =
  120. [UIAlertController alertControllerWithTitle:nil
  121. message:message
  122. preferredStyle:UIAlertControllerStyleAlert];
  123. __weak UIAlertController *weakPrompt = prompt;
  124. UIAlertAction *cancelAction =
  125. [UIAlertAction actionWithTitle:kCancel
  126. style:UIAlertActionStyleCancel
  127. handler:^(UIAlertAction * _Nonnull action) {
  128. completion(NO, nil);
  129. }];
  130. UIAlertAction *okAction = [UIAlertAction actionWithTitle:kOK
  131. style:UIAlertActionStyleDefault
  132. handler:^(UIAlertAction * _Nonnull action) {
  133. UIAlertController *strongPrompt = weakPrompt;
  134. completion(YES, strongPrompt.textFields[0].text);
  135. }];
  136. [prompt addTextFieldWithConfigurationHandler:^(UITextField *_Nonnull textField) {
  137. textField.keyboardType = keyboardType;
  138. }];
  139. [prompt addAction:cancelAction];
  140. [prompt addAction:okAction];
  141. [self presentViewController:prompt animated:YES completion:nil];
  142. } else {
  143. SimpleTextPromptDelegate *prompt =
  144. [[SimpleTextPromptDelegate alloc] initWithCompletionHandler:completion];
  145. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
  146. message:message
  147. delegate:prompt
  148. cancelButtonTitle:@"Cancel"
  149. otherButtonTitles:@"Ok", nil];
  150. alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
  151. [alertView show];
  152. }
  153. }
  154. - (void)showSpinner:(nullable void(^)(void))completion {
  155. if (self.useStatusBarSpinner) {
  156. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  157. completion();
  158. return;
  159. }
  160. if ([self supportsAlertController]) {
  161. [self showModernSpinner:completion];
  162. } else {
  163. [self showIOS7Spinner:completion];
  164. }
  165. }
  166. - (void)showModernSpinner:(nullable void (^)(void))completion {
  167. UIAlertController *pleaseWaitAlert =
  168. objc_getAssociatedObject(self,
  169. (__bridge const void *)kPleaseWaitAssociatedObjectKey);
  170. if (pleaseWaitAlert) {
  171. if (completion) {
  172. completion();
  173. }
  174. return;
  175. }
  176. pleaseWaitAlert = [UIAlertController alertControllerWithTitle:nil
  177. message:@"Please Wait...\n\n\n\n"
  178. preferredStyle:UIAlertControllerStyleAlert];
  179. UIActivityIndicatorView *spinner =
  180. [[UIActivityIndicatorView alloc]
  181. initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
  182. spinner.color = [UIColor blackColor];
  183. spinner.center = CGPointMake(pleaseWaitAlert.view.bounds.size.width / 2,
  184. pleaseWaitAlert.view.bounds.size.height / 2);
  185. spinner.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin |
  186. UIViewAutoresizingFlexibleTopMargin |
  187. UIViewAutoresizingFlexibleLeftMargin |
  188. UIViewAutoresizingFlexibleRightMargin;
  189. [spinner startAnimating];
  190. [pleaseWaitAlert.view addSubview:spinner];
  191. objc_setAssociatedObject(self,
  192. (__bridge const void *)(kPleaseWaitAssociatedObjectKey),
  193. pleaseWaitAlert,
  194. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  195. [self presentViewController:pleaseWaitAlert animated:YES completion:completion];
  196. }
  197. - (void)showIOS7Spinner:(nullable void (^)(void))completion {
  198. UIWindow *pleaseWaitWindow =
  199. objc_getAssociatedObject(self,
  200. (__bridge const void *)kPleaseWaitAssociatedObjectKey);
  201. if (pleaseWaitWindow) {
  202. if (completion) {
  203. completion();
  204. }
  205. return;
  206. }
  207. pleaseWaitWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  208. pleaseWaitWindow.backgroundColor = [UIColor clearColor];
  209. pleaseWaitWindow.windowLevel = UIWindowLevelStatusBar - 1;
  210. UIView *pleaseWaitView = [[UIView alloc] initWithFrame:pleaseWaitWindow.bounds];
  211. pleaseWaitView.autoresizingMask = UIViewAutoresizingFlexibleWidth |
  212. UIViewAutoresizingFlexibleHeight;
  213. pleaseWaitView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  214. UIActivityIndicatorView *spinner =
  215. [[UIActivityIndicatorView alloc]
  216. initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
  217. spinner.center = pleaseWaitView.center;
  218. [pleaseWaitView addSubview:spinner];
  219. [spinner startAnimating];
  220. pleaseWaitView.layer.opacity = 0.0;
  221. [self.view addSubview:pleaseWaitView];
  222. [pleaseWaitWindow addSubview:pleaseWaitView];
  223. [pleaseWaitWindow makeKeyAndVisible];
  224. objc_setAssociatedObject(self,
  225. (__bridge const void *)(kPleaseWaitAssociatedObjectKey),
  226. pleaseWaitWindow,
  227. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  228. [UIView animateWithDuration:0.5f animations:^{
  229. pleaseWaitView.layer.opacity = 1.0f;
  230. } completion:^(BOOL finished) {
  231. if (completion) {
  232. completion();
  233. }
  234. }];
  235. }
  236. - (void)hideSpinner:(nullable void(^)(void))completion {
  237. if (self.useStatusBarSpinner) {
  238. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  239. completion();
  240. return;
  241. }
  242. if ([self supportsAlertController]) {
  243. [self hideModernSpinner:completion];
  244. } else {
  245. [self hideIOS7Spinner:completion];
  246. }
  247. }
  248. - (void)hideModernSpinner:(nullable void(^)(void))completion {
  249. UIAlertController *pleaseWaitAlert =
  250. objc_getAssociatedObject(self,
  251. (__bridge const void *)kPleaseWaitAssociatedObjectKey);
  252. [pleaseWaitAlert dismissViewControllerAnimated:YES completion:completion];
  253. objc_setAssociatedObject(self,
  254. (__bridge const void *)(kPleaseWaitAssociatedObjectKey),
  255. nil,
  256. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  257. }
  258. - (void)hideIOS7Spinner:(nullable void(^)(void))completion {
  259. UIWindow *pleaseWaitWindow =
  260. objc_getAssociatedObject(self,
  261. (__bridge const void *)kPleaseWaitAssociatedObjectKey);
  262. UIView *pleaseWaitView;
  263. pleaseWaitView = pleaseWaitWindow.subviews.firstObject;
  264. [UIView animateWithDuration:0.5f animations:^{
  265. pleaseWaitView.layer.opacity = 0.0f;
  266. } completion:^(BOOL finished) {
  267. [pleaseWaitWindow resignKeyWindow];
  268. objc_setAssociatedObject(self,
  269. (__bridge const void *)(kPleaseWaitAssociatedObjectKey),
  270. nil,
  271. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  272. if (completion) {
  273. completion();
  274. }
  275. }];
  276. }
  277. @end
  278. @implementation SimpleTextPromptDelegate {
  279. AlertPromptCompletionBlock _completionHandler;
  280. SimpleTextPromptDelegate *_retainedSelf;
  281. }
  282. - (instancetype)initWithCompletionHandler:(AlertPromptCompletionBlock)completionHandler {
  283. self = [super init];
  284. if (self) {
  285. _completionHandler = completionHandler;
  286. _retainedSelf = self;
  287. }
  288. return self;
  289. }
  290. - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
  291. if (buttonIndex == alertView.firstOtherButtonIndex) {
  292. _completionHandler(YES, [alertView textFieldAtIndex:0].text);
  293. } else {
  294. _completionHandler(NO, nil);
  295. }
  296. _completionHandler = nil;
  297. _retainedSelf = nil;
  298. }
  299. @end