How to show UIAlertController from Appdelegate

前端 未结 6 1721
后悔当初
后悔当初 2020-11-30 01:32

I\'m working with PushNotification on iOS app. I would like to show a UIalertcontroller when the app receive a notification.

I try this code below in the AppDelegate

6条回答
  •  眼角桃花
    2020-11-30 02:11

    For the easiness, I used category

    UIAlertController+UIWindow.h

    @interface UIAlertController (UIWindow)
    
    - (void)show;
    - (void)show:(BOOL)animated;
    
    @end
    

    UIAlertController+UIWindow.m

    #import 
    
    @interface UIAlertController (Private)
    
    @property (nonatomic, strong) UIWindow *alertWindow;
    
    @end
    
    @implementation UIAlertController (Private)
    
    @dynamic alertWindow;
    
    - (void)setAlertWindow:(UIWindow *)alertWindow {
        objc_setAssociatedObject(self, @selector(alertWindow), alertWindow, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    - (UIWindow *)alertWindow {
        return objc_getAssociatedObject(self, @selector(alertWindow));
    }
    
    @end
    
    @implementation UIAlertController (UIWindow)
    
    - (void)show {
        [self show:YES];
    }
    
    - (void)show:(BOOL)animated {
        [self setupWindow];
        [self.alertWindow.rootViewController presentViewController:self animated:animated completion:nil];
    }
    
    - (void)setupWindow {
        self.alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        self.alertWindow.rootViewController = [[UIViewController alloc] init];
    
        id delegate = [UIApplication sharedApplication].delegate;
        if ([delegate respondsToSelector:@selector(window)]) {
            self.alertWindow.tintColor = delegate.window.tintColor;
        }
    
        UIWindow *topWindow = [UIApplication sharedApplication].windows.lastObject;
        self.alertWindow.windowLevel = topWindow.windowLevel + 1;
    
        [self.alertWindow makeKeyAndVisible];
    }
    
    - (void)viewDidDisappear:(BOOL)animated {
        [super viewDidDisappear:animated];
    
        // precaution to insure window gets destroyed
        self.alertWindow.hidden = YES;
        self.alertWindow = nil;
    }
    

    Use:

    UIAlertController *alertController;
    // -- code --
    [alertController show];
    

提交回复
热议问题