27

I'm working on a ViewController with code (no storyboard). I'm trying to add and AlertController

I have declare propery in .m

@property (nonatomic, strong) UIAlertController *alertController;

And init in loadview method

//alertviewController
    _alertController = [[UIAlertController alloc]initWithNibName:nil bundle:nil];

And call the alertview in viewDidLoad:

_alertController = [UIAlertController alertControllerWithTitle:@"Error display content" message:@"Error connecting to server, no local database" preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                LandingPageViewController *viewController = [[LandingPageViewController alloc] initWithNibName:nil bundle:nil];
    //            viewController.showNavBarBackButton = YES;
                [[AppDelegate sharedAppDelegate].rootViewController cPushViewController:viewController];
}];
[_alertController addAction:ok];
[self presentViewController:_alertController animated:YES completion:nil];

I dont' know why the alert is not showing up. Some thing wrong with my code. How to set up and call alertViewController programmatically?

11
  • Hi tried but there is error no visible interface for 'UIAlertController' declares the selector 'show'. [_alertController show]; Commented Aug 1, 2016 at 15:16
  • Remove this line _alertController = [[UIAlertController alloc]initWithNibName:nil bundle:nil]; I'm not sure if that will fix the problem, but it's not needed, especially not in loadView, (did you mean viewDidLoad?) Commented Aug 1, 2016 at 15:18
  • try calling this alert in viewDidAppear Commented Aug 1, 2016 at 15:21
  • Hi i put the calling code in viewdidAppear the alert show up but crash with this error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modally an active controller <StampCollectiblesMainViewController: 0x7b58d110>.' Commented Aug 1, 2016 at 15:25
  • it probably crashes on the button tap. which means make sure the alert dismisses and then the push takes place. call the push after delay Commented Aug 1, 2016 at 15:45

4 Answers 4

72
- (void)logoutButtonPressed
{
     UIAlertController * alert = [UIAlertController
                                 alertControllerWithTitle:@"Logout"
                                 message:@"Are You Sure Want to Logout!"
                                 preferredStyle:UIAlertControllerStyleAlert];

    //Add Buttons

    UIAlertAction* yesButton = [UIAlertAction
                                actionWithTitle:@"Yes"
                                style:UIAlertActionStyleDefault
                                handler:^(UIAlertAction * action) {
                                    //Handle your yes please button action here
                                    [self clearAllData];
                                }];

    UIAlertAction* noButton = [UIAlertAction
                               actionWithTitle:@"Cancel"
                               style:UIAlertActionStyleDefault
                               handler:^(UIAlertAction * action) {
                                   //Handle no, thanks button
                               }];

    //Add your buttons to alert controller

    [alert addAction:yesButton];
    [alert addAction:noButton];

    [self presentViewController:alert animated:YES completion:nil];
}
Sign up to request clarification or add additional context in comments.

8 Comments

hi where to call the [self presentViewController:alert animated:YES completion:nil]; seem can not call in viewdidload
Hi it working when i create separate method and call in viewdidload but there a warning in console: Presenting view controllers on detached view controllers is discouraged
where r u performing ur alert controller, it may be button click or on some method, use above complete code in one method and call it in ur desire place. hope u got it
Hi my purpose is when user come to the viewcontroller the app will check whether coredata has record or not. if not and there is no internet connection . the app will show an error "no databae no internet connection" and move to home page!
@LêKhánhVinh it is not good to have alert view controller in viewDidLoad. u can check after view get loaded
|
7

In Xcode 9.4.1

Create alert function globally and use every where.

//Alert function
- (void) showAlertMsg:(UIViewController *)viewController title:(NSString *)title message:(NSString *)message {

    UIAlertController * alert = [UIAlertController alertControllerWithTitle : title
                                                                    message : message
                                                             preferredStyle : UIAlertControllerStyleAlert];

    UIAlertAction * ok = [UIAlertAction
                          actionWithTitle:@"OK"
                          style:UIAlertActionStyleDefault
                          handler:^(UIAlertAction * action)
                          { }];

    [alert addAction:ok];
    dispatch_async(dispatch_get_main_queue(), ^{
        [viewController presentViewController:alert animated:YES completion:nil];
    });

}

Call like this in your required place.

Import that class and create instance

//Ex:
GlobalClassViewController *gcvc = [[GlobalClassViewController alloc]init];

//Call alert function with instance
[gcvc showAlertMsg:self title:@"" message:placeholderText];

How would I create a UIAlertView in Swift?

2 Comments

The dispatch_async helped me get past some issues where my alerts weren't appearing because they were inadvertently created on view which were going out of scope.
The dispatch_async is necessary in iOS13+ with UISplitViewController on iPad (no scenes, no Storyboards). It is not required in iOS12 and lower. UI just locks up without showing the alert otherwise.
2

And in Swift >=3:

  let alertController = UIAlertController(title: "Some Error",
                                               message: "Pleas confirm?",
                                               preferredStyle: .alert)

  let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
            alertController.addAction(defaultAction)

  self?.present(alertController, animated: true, completion: nil)

4 Comments

hi so where is the place to place the code whenever user come to that viewcontroller and app has finished checked for some logic (for example no coredata to show?)
It's up to you, you can put it in viewDidLoad if you'd like it to be displayed when the user comes to that view or you can have it fired on a certain button press via IBAction
Hi i found put on view did load not working for alertViewController. Need to be in viewDidAppear
Nice catch, that will work or it should also work as an IBAction
0

Create global Alert controller that is accessible in all view controllers using extension.
Create an extension of UIViewController with your function to display alert with required parameter arguments.

extension UIViewController {

      func displayalert(title:String, message:String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

            alert.dismiss(animated: true, completion: nil)

        })))

        self.present(alert, animated: true, completion: nil)


      }
}


Now call this function from your view controller:

class TestViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.displayalert(title: <String>, message: <String>)
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.