aboutsummaryrefslogtreecommitdiffhomepage
path: root/AuthSamples/Sample/UIViewController+Alerts.m
blob: 76ef06729e558731607beec9739f663b089f3d2f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
 * Copyright 2017 Google
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import "UIViewController+Alerts.h"

#import <objc/runtime.h>

/*! @var kPleaseWaitAssociatedObjectKey
    @brief Key used to identify the "please wait" spinner associated object.
 */
static NSString *const kPleaseWaitAssociatedObjectKey =
    @"_UIViewControllerAlertCategory_PleaseWaitScreenAssociatedObject";

/*! @var kUseStatusBarSpinnerAssociatedObjectKey
    @brief The address of this constant is the key used to identify the "use status bar spinner"
        associated object.
 */
static const void *const kUseStatusBarSpinnerAssociatedObjectKey;

/*! @var kOK
    @brief Text for an 'OK' button.
 */
static NSString *const kOK = @"OK";

/*! @var kCancel
    @brief Text for an 'Cancel' button.
 */
static NSString *const kCancel = @"Cancel";

/*! @class SimpleTextPromptDelegate
    @brief A @c UIAlertViewDelegate which allows @c UIAlertView to be used with blocks more easily.
 */
@interface SimpleTextPromptDelegate : NSObject <UIAlertViewDelegate>

/*! @fn init
    @brief Please use initWithCompletionHandler.
 */
- (nullable instancetype)init NS_UNAVAILABLE;

/*! @fn initWithCompletionHandler:
    @brief Designated initializer.
    @param completionHandler The block to call when the alert view is dismissed.
 */
- (nullable instancetype)initWithCompletionHandler:(AlertPromptCompletionBlock)completionHandler
    NS_DESIGNATED_INITIALIZER;

@end

@implementation UIViewController (Alerts)

- (void)setUseStatusBarSpinner:(BOOL)useStatusBarSpinner {
  objc_setAssociatedObject(self,
                           &kUseStatusBarSpinnerAssociatedObjectKey,
                           useStatusBarSpinner ? @(YES) : nil,
                           OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)useStatusBarSpinner {
  return objc_getAssociatedObject(self, &kUseStatusBarSpinnerAssociatedObjectKey) ? YES : NO;
}

/*! @fn supportsAlertController
    @brief Determines if the current platform supports @c UIAlertController.
    @return YES if the current platform supports @c UIAlertController.
 */
- (BOOL)supportsAlertController {
  return NSClassFromString(@"UIAlertController") != nil;
}

- (void)showMessagePrompt:(NSString *)message {
  [self showMessagePromptWithTitle:nil message:message showCancelButton:NO completion:nil];
}

- (void)showMessagePromptWithTitle:(nullable NSString *)title
                           message:(NSString *)message
                  showCancelButton:(BOOL)showCancelButton
                        completion:(nullable AlertPromptCompletionBlock)completion {
  if (message) {
    [UIPasteboard generalPasteboard].string = message;
  }
  if ([self supportsAlertController]) {
    UIAlertController *alert =
        [UIAlertController alertControllerWithTitle:title
                                            message:message
                                     preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction =
        [UIAlertAction actionWithTitle:kOK
                                 style:UIAlertActionStyleDefault
                               handler:^(UIAlertAction * _Nonnull action) {
          if (completion) {
            completion(YES, nil);
          }
        }];
    [alert addAction:okAction];

    if (showCancelButton) {
      UIAlertAction *cancelAction =
          [UIAlertAction actionWithTitle:kCancel
                                   style:UIAlertActionStyleCancel
                                 handler:^(UIAlertAction * _Nonnull action) {
            completion(NO, nil);
          }];
      [alert addAction:cancelAction];
    }
    [self presentViewController:alert animated:YES completion:nil];
  } else {
    UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle:title
                                   message:message
                                  delegate:nil
                         cancelButtonTitle:nil
                         otherButtonTitles:kOK, nil];
    [alert show];
  }
}

- (void)showTextInputPromptWithMessage:(NSString *)message
                       completionBlock:(AlertPromptCompletionBlock)completion {
  [self showTextInputPromptWithMessage:message
                          keyboardType:UIKeyboardTypeDefault
                       completionBlock:completion];
}

- (void)showTextInputPromptWithMessage:(NSString *)message
                          keyboardType:(UIKeyboardType)keyboardType
                       completionBlock:(nonnull AlertPromptCompletionBlock)completion {
  if ([self supportsAlertController]) {
      UIAlertController *prompt =
          [UIAlertController alertControllerWithTitle:nil
                                              message:message
                                       preferredStyle:UIAlertControllerStyleAlert];
      __weak UIAlertController *weakPrompt = prompt;
      UIAlertAction *cancelAction =
          [UIAlertAction actionWithTitle:kCancel
                                   style:UIAlertActionStyleCancel
                                 handler:^(UIAlertAction * _Nonnull action) {
            completion(NO, nil);
          }];
      UIAlertAction *okAction = [UIAlertAction actionWithTitle:kOK
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * _Nonnull action) {
            UIAlertController *strongPrompt = weakPrompt;
            completion(YES, strongPrompt.textFields[0].text);
      }];
      [prompt addTextFieldWithConfigurationHandler:^(UITextField *_Nonnull textField) {
        textField.keyboardType = keyboardType;
      }];
      [prompt addAction:cancelAction];
      [prompt addAction:okAction];
      [self presentViewController:prompt animated:YES completion:nil];
  } else {
    SimpleTextPromptDelegate *prompt =
        [[SimpleTextPromptDelegate alloc] initWithCompletionHandler:completion];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                        message:message
                                                       delegate:prompt
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:@"Ok", nil];
    alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alertView show];
  }
}

- (void)showSpinner:(nullable void(^)(void))completion {
  if (self.useStatusBarSpinner) {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    completion();
    return;
  }
  if ([self supportsAlertController]) {
    [self showModernSpinner:completion];
  } else {
    [self showIOS7Spinner:completion];
  }
}

- (void)showModernSpinner:(nullable void (^)(void))completion {
  UIAlertController *pleaseWaitAlert =
      objc_getAssociatedObject(self,
                               (__bridge const void *)kPleaseWaitAssociatedObjectKey);
  if (pleaseWaitAlert) {
    if (completion) {
      completion();
    }
    return;
  }
  pleaseWaitAlert = [UIAlertController alertControllerWithTitle:nil
                                                        message:@"Please Wait...\n\n\n\n"
                                                 preferredStyle:UIAlertControllerStyleAlert];

  UIActivityIndicatorView *spinner =
      [[UIActivityIndicatorView alloc]
          initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
  spinner.color = [UIColor blackColor];
  spinner.center = CGPointMake(pleaseWaitAlert.view.bounds.size.width / 2,
      pleaseWaitAlert.view.bounds.size.height / 2);
  spinner.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin |
      UIViewAutoresizingFlexibleTopMargin |
      UIViewAutoresizingFlexibleLeftMargin |
      UIViewAutoresizingFlexibleRightMargin;
  [spinner startAnimating];
  [pleaseWaitAlert.view addSubview:spinner];

  objc_setAssociatedObject(self,
      (__bridge const void *)(kPleaseWaitAssociatedObjectKey),
      pleaseWaitAlert,
      OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  [self presentViewController:pleaseWaitAlert animated:YES completion:completion];
}

- (void)showIOS7Spinner:(nullable void (^)(void))completion {
  UIWindow *pleaseWaitWindow =
      objc_getAssociatedObject(self,
                               (__bridge const void *)kPleaseWaitAssociatedObjectKey);

  if (pleaseWaitWindow) {
    if (completion) {
      completion();
    }
    return;
  }

  pleaseWaitWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  pleaseWaitWindow.backgroundColor = [UIColor clearColor];
  pleaseWaitWindow.windowLevel = UIWindowLevelStatusBar - 1;

  UIView *pleaseWaitView = [[UIView alloc] initWithFrame:pleaseWaitWindow.bounds];
  pleaseWaitView.autoresizingMask = UIViewAutoresizingFlexibleWidth |
      UIViewAutoresizingFlexibleHeight;
  pleaseWaitView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  UIActivityIndicatorView *spinner =
      [[UIActivityIndicatorView alloc]
          initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
  spinner.center = pleaseWaitView.center;
  [pleaseWaitView addSubview:spinner];
  [spinner startAnimating];

  pleaseWaitView.layer.opacity = 0.0;
  [self.view addSubview:pleaseWaitView];

  [pleaseWaitWindow addSubview:pleaseWaitView];

  [pleaseWaitWindow makeKeyAndVisible];

  objc_setAssociatedObject(self,
      (__bridge const void *)(kPleaseWaitAssociatedObjectKey),
      pleaseWaitWindow,
      OBJC_ASSOCIATION_RETAIN_NONATOMIC);

  [UIView animateWithDuration:0.5f animations:^{
    pleaseWaitView.layer.opacity = 1.0f;
  } completion:^(BOOL finished) {
    if (completion) {
      completion();
    }
  }];
}

- (void)hideSpinner:(nullable void(^)(void))completion {
  if (self.useStatusBarSpinner) {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    completion();
    return;
  }
  if ([self supportsAlertController]) {
    [self hideModernSpinner:completion];
  } else {
    [self hideIOS7Spinner:completion];
  }
}

- (void)hideModernSpinner:(nullable void(^)(void))completion {
  UIAlertController *pleaseWaitAlert =
      objc_getAssociatedObject(self,
                               (__bridge const void *)kPleaseWaitAssociatedObjectKey);

  [pleaseWaitAlert dismissViewControllerAnimated:YES completion:completion];

  objc_setAssociatedObject(self,
      (__bridge const void *)(kPleaseWaitAssociatedObjectKey),
      nil,
      OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)hideIOS7Spinner:(nullable void(^)(void))completion {
  UIWindow *pleaseWaitWindow =
      objc_getAssociatedObject(self,
                               (__bridge const void *)kPleaseWaitAssociatedObjectKey);

  UIView *pleaseWaitView;
  pleaseWaitView = pleaseWaitWindow.subviews.firstObject;

  [UIView animateWithDuration:0.5f animations:^{
    pleaseWaitView.layer.opacity = 0.0f;
  } completion:^(BOOL finished) {
    [pleaseWaitWindow resignKeyWindow];
    objc_setAssociatedObject(self,
        (__bridge const void *)(kPleaseWaitAssociatedObjectKey),
        nil,
        OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (completion) {
      completion();
    }
  }];
}

@end

@implementation SimpleTextPromptDelegate {
  AlertPromptCompletionBlock _completionHandler;
  SimpleTextPromptDelegate *_retainedSelf;
}

- (instancetype)initWithCompletionHandler:(AlertPromptCompletionBlock)completionHandler {
  self = [super init];
  if (self) {
    _completionHandler = completionHandler;
    _retainedSelf = self;
  }
  return self;
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
  if (buttonIndex == alertView.firstOtherButtonIndex) {
    _completionHandler(YES, [alertView textFieldAtIndex:0].text);
  } else {
    _completionHandler(NO, nil);
  }
  _completionHandler = nil;
  _retainedSelf = nil;
}

@end