[ios] UIAlertView first deprecated IOS 9

I have tried several ways to use UIAlertController,instead of UIAlertView. I tried several ways but I cannot make the alert action work. Here is my code that works fine in IOS 8 and IOS 9 but is showing up with deprecated flags. I tried the elegant suggestion below but I can't make it function in this context. I need to submit my app and this is the last thing to address. Thank You for any further suggestions. I am a newbie.

#pragma mark - BUTTONS ================================
- (IBAction)showModesAction:(id)sender {
NSLog(@"iapMade: %d", iapMade3);

// IAP MADE ! ===========================================
if (!iapMade3) {

    //start game here
    gamePlaysCount++;
    [[NSUserDefaults standardUserDefaults]setInteger:gamePlaysCount forKey:@"gamePlaysCount"];
    NSLog(@"playsCount: %ld", (long)gamePlaysCount);

    if (gamePlaysCount >= 4) {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Basic"
                                                     message: THREE_PLAYS_LIMIT_MESSAGE
                                                    delegate:self
                                           cancelButtonTitle:@"Yes, please"
                                           otherButtonTitles:@"No, thanks", nil];
       [alert show];

        NSString *path = [[NSBundle mainBundle] pathForResource:@"cow" ofType:@"wav"];
        _pop =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
        [_pop play];
        [self dismissViewControllerAnimated:true completion:nil];

    } else {
        if (gamePlaysCount == 1)  {
            // Create & store the next 5 mins when player gets 3 more lives
            nextDateToPlay = [[NSDate date] dateByAddingTimeInterval:60*60*0.1];
            NSLog(@"CURRENT DATE: %@", [NSDate date]);
            NSLog(@"NEXT DAY: %@", nextDateToPlay);
            [[NSUserDefaults standardUserDefaults]setObject: nextDateToPlay    forKey:@"nextDateToPlay"];
            NSLog(@"nextDateToPlay: %@", nextDateToPlay);

            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Basic"
                                                           message:  THREE_PLAYS_LIMIT_MESSAGE2
                                                          delegate:self
                                                 cancelButtonTitle:@"Got it!"
                                                 otherButtonTitles:@"Start", nil];
            [alert show];
        } else {

            if (gamePlaysCount == 3)  {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Basic"
                                                               message: THREE_PLAYS_LIMIT_MESSAGE3
                                                              delegate:self
                                                     cancelButtonTitle:@"Yep, I Know!"
                                                     otherButtonTitles:@"Start", nil];
                [alert show];
            }
        }
    }
}

}

// IAP NOT MADE =============================

#pragma mark - ALERTVIEW DELEGATE ============================

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

if ([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:@"Yes, please"]) {

    UIStoryboard *storyboard = self.storyboard;
    MenuViewController *svc = [storyboard instantiateViewControllerWithIdentifier:@"Store"];
    svc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:svc animated:YES completion:nil];

        }

}

This question is related to ios objective-c uialertview uialertcontroller

The answer is


Make UIAlertController+AlertController Category as:

UIAlertController+AlertController.h

typedef void (^UIAlertCompletionBlock) (UIAlertController *alertViewController, NSInteger buttonIndex);

@interface UIAlertController (AlertController)

+ (instancetype)showAlertIn:(UIViewController *)controller
                  WithTitle:(NSString *)title
                    message:(NSString *)message
          cancelButtonTitle:(NSString *)cancelButtonTitle
          otherButtonTitles:(NSString *)otherButtonTitle
                   tapBlock:(UIAlertCompletionBlock)tapBlock;
@end

UIAlertController+AlertController.m

@implementation UIAlertController (NTAlertController)

+ (instancetype)showAlertIn:(UIViewController *)controller
                  WithTitle:(NSString *)title
                    message:(NSString *)message
          cancelButtonTitle:(NSString *)cancelButtonTitle
          otherButtonTitles:(NSString *)otherButtonTitle
                   tapBlock:(UIAlertCompletionBlock)tapBlock {

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

    if(cancelButtonTitle != nil) {

        UIAlertAction *cancelButton = [UIAlertAction
                                       actionWithTitle:cancelButtonTitle
                                       style:UIAlertActionStyleCancel
                                       handler:^(UIAlertAction *action)
                                       {
                                           tapBlock(alertController, ALERTACTION_CANCEL); // CANCEL BUTTON CALL BACK ACTION
                                       }];
        [alertController addAction:cancelButton];

    }

    if(otherButtonTitle != nil) {

        UIAlertAction *otherButton = [UIAlertAction
                                   actionWithTitle:otherButtonTitle
                                   style:UIAlertActionStyleDefault
                                   handler:^(UIAlertAction *action)
                                   {
                                       tapBlock(alertController, ALERTACTION_OTHER); // OTHER BUTTON CALL BACK ACTION
                                   }];

        [alertController addAction:otherButton];
    }

    [controller presentViewController:alertController animated:YES completion:nil];

    return alertController;
}

@end

in your ViewController.m

[UIAlertController showAlertIn:self WithTitle:@"" message:@"" cancelButtonTitle:@"Cancel" otherButtonTitles:@"Other" tapBlock:^(UIAlertController *alertController, NSInteger index){

 if(index == ALERTACTION_CANCEL){

 // CANCEL BUTTON ACTION
 }else
if(index == ALERTACTION_OTHER){

 // OTHER BUTTON ACTION
 }

 [alertController dismissViewControllerAnimated:YES completion:nil];

 }];

NOTE: If you want to add more than two buttons then add another more UIAlertAction to the UIAlertController.


Xcode 8 + Swift

Assuming self is a UIViewController:

func displayAlert() {
    let alert = UIAlertController(title: "Test",
                                  message: "I am a modal alert",
                                  preferredStyle: .alert)
    let defaultButton = UIAlertAction(title: "OK",
                                      style: .default) {(_) in
        // your defaultButton action goes here
    }
    
    alert.addAction(defaultButton)
    present(alert, animated: true) { 
        // completion goes here
    }
}

Use UIAlertController instead of UIAlertView

-(void)showMessage:(NSString*)message withTitle:(NSString *)title
{
UIAlertController * alert=   [UIAlertController
                              alertControllerWithTitle:title
                              message:message
                              preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

    //do something when click button
}];
[alert addAction:okAction];
UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[vc presentViewController:alert animated:YES completion:nil];
}

//Calling     
[self showMessage:@"There is no internet connection for this device"
                    withTitle:@"Error"];

//Method

-(void)showMessage:(NSString*)message withTitle:(NSString *)title
{

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

    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

        //do something when click button
    }];
    [alert addAction:okAction];
    UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
    [vc presentViewController:alert animated:YES completion:nil];
}

If you want to use this alert in NSObject class you should use like:

-(void)showMessage:(NSString*)message withTitle:(NSString *)title{
dispatch_async(dispatch_get_main_queue(), ^{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }]];

    [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alertController animated:YES completion:^{
    }];
});
}

Check this:

UIAlertController *alertctrl =[UIAlertController alertControllerWithTitle:@"choose Image" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *camera =[UIAlertAction actionWithTitle:@"camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self Action];  //call Action need to perform 
    }];

[alertctrl addAction:camera];
-(void)Action 

{

}

-(void)showAlert{

    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Title"
                                                                   message:"Message"
                                                            preferredStyle:UIAlertControllerStyleAlert];

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

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

[self showAlert]; // calling Method


I tried the above methods, and no one can show the alert view, only when I put the presentViewController: method in a dispatch_async sentence:

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

Refer to Alternative to UIAlertView for iOS 9?.


 UIAlertController * alert = [UIAlertController
                                 alertControllerWithTitle:@"Are you sure you want to logout?"
                                 message:@""
                                 preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* yesButton = [UIAlertAction
                                actionWithTitle:@"Logout"
                                style:UIAlertActionStyleDestructive
                                handler:^(UIAlertAction * action)
                                {

                                }];

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

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

    [self presentViewController:alert animated:YES completion:nil];

Swift version of new implementation is :

 let alert = UIAlertController(title: "Oops!", message:"your message", preferredStyle: .Alert)
 alert.addAction(UIAlertAction(title: "Okay.", style: .Default) { _ in })
 self.presentViewController(alert, animated: true){}

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to uialertview

UIAlertView first deprecated IOS 9 UIAlertController custom font, size, color How to add an action to a UIAlertView button using Swift iOS Writing handler for UIAlertAction How would I create a UIAlertView in Swift? Display UIViewController as Popup in iPhone Adding a simple UIAlertView

Examples related to uialertcontroller

UIAlertView first deprecated IOS 9 Get input value from TextField in iOS alert in Swift How to present UIAlertController when not in a view controller? UIAlertController custom font, size, color Presenting a UIAlertController properly on an iPad using iOS 8 Writing handler for UIAlertAction How would I create a UIAlertView in Swift?