Search code examples
iosobjective-ciphoneswift3uialertcontroller

How to show UIAlertController from Appdelegate


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:

[self.window.rootViewController presentViewController:alert animated:YES completion:nil];

But the UIAlertcontroller is showing in the root View (First screen) and for other uiviewcontroller i got warning or the app crashes.


Solution

  • try this

    Objective-C

    UIWindow* topWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    topWindow.rootViewController = [UIViewController new];
    topWindow.windowLevel = UIWindowLevelAlert + 1;
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"APNS" message:@"received Notification" preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK",@"confirm") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        // continue your work
    
        // important to hide the window after work completed.
        // this also keeps a reference to the window until the action is invoked.
        topWindow.hidden = YES; // if you want to hide the topwindow then use this
        topWindow = nil; // if you want to remove the topwindow then use this 
    }]];
    
    [topWindow makeKeyAndVisible];
    [topWindow.rootViewController presentViewController:alert animated:YES completion:nil];
    

    Swift3 and above

    var topWindow: UIWindow? = UIWindow(frame: UIScreen.main.bounds)
    topWindow?.rootViewController = UIViewController()
    topWindow?.windowLevel = UIWindow.Level.alert + 1
    
    let alert = UIAlertController(title: "APNS", message: "received Notification", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .cancel) { _ in
        // continue your work
    
        // important to hide the window after work completed.
        // this also keeps a reference to the window until the action is invoked.
        topWindow?.isHidden = true // if you want to hide the topwindow then use this
        topWindow = nil // if you want to hide the topwindow then use this
     })
    
    topWindow?.makeKeyAndVisible()
    topWindow?.rootViewController?.present(alert, animated: true, completion: nil)
    

    Detail description: http://www.thecave.com/2015/09/28/how-to-present-an-alert-view-using-uialertcontroller-when-you-dont-have-a-view-controller/