35

I have see more so answers , but nothing helped.Here is my older alert and action for that

override func viewWillAppear(animated: Bool) {
    if Reachability.isConnectedToNetwork() == true {
        print("internet connection ok")
    } else 
    {
        print("internet not ok")
        let alertView: UIAlertView = UIAlertView(title: "Alert ", message: "connect to internet", delegate: self, cancelButtonTitle: "settings", otherButtonTitles: "cancel")
        alertView.show()
        return       
    }       
}

func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int)
{
    if buttonIndex == 0 {
        //This will open ios devices wifi settings
        UIApplication.sharedApplication().openURL(NSURL(string: "prefs:root")!)
    }
    else if buttonIndex == 1
    {
        //TODO for cancel
        exit(0) 
    }
}

In that i am getting warning :

'UIAlertView' was deprecated in iOS 9.0. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead

I tried :

let alert = UIAlertController(title: "Alert", message: "My Alert for test", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: {    (action:UIAlertAction!) in 
        print("you have pressed the Cancel button")
    }))
self.presentViewController(alert, animated: true, completion: nil)

But to add two button and add the index path of button press method link my older code,I am not able to do that. Nothing action happening fro my uialert button,

Please help me out,How can i remove that warnings and recode my Uialert with my two button action.

I am new to swift.Your help will be useful.Thanks!

spassas
  • 4,778
  • 2
  • 31
  • 39
user5513630
  • 1,709
  • 8
  • 24
  • 48
  • 1
    Why you need button index in above case ? Write the code that need to be executed for each of those button click in it's handler block/closure. – Midhun MP Apr 04 '16 at 05:28
  • @user5513630 if we use UIAlertCOntroller instead of UIAlertView , then can we use this function "func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int){} " if not then what is the alternative? please help me , i am new – ArgaPK Nov 01 '17 at 06:33
  • @MidhunMP if we use UIAlertCOntroller instead of UIAlertView , then can we use this function "func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int){} " if not then what is the alternative? please help me , i am new – ArgaPK Nov 01 '17 at 06:34
  • 1
    @ArgaPK: You can't use that method. For each button there is a closure block (Refer UIAlertAction), when that button is clicked corresponding closure will be executed. Check the following answers to get a clear idea – Midhun MP Nov 01 '17 at 06:55
  • @MidhunMP Thank You – ArgaPK Nov 01 '17 at 16:55

8 Answers8

73

See this Code Destructive and OK buttons in UIAlertController:

let alertController = UIAlertController(title: "Destructive", message: "Simple alertView demo with Destructive and Ok.", preferredStyle: UIAlertControllerStyle.alert) //Replace UIAlertControllerStyle.Alert by UIAlertControllerStyle.alert
let DestructiveAction = UIAlertAction(title: "Destructive", style: UIAlertActionStyle.Destructive) {
    (result : UIAlertAction) -> Void in
    print("Destructive")
}

// Replace UIAlertActionStyle.Default by UIAlertActionStyle.default
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
    (result : UIAlertAction) -> Void in
    print("OK")
}

alertController.addAction(DestructiveAction)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)

Swift 3:

let alertController = UIAlertController(title: "Destructive", message: "Simple alertView demo with Destructive and Ok.", preferredStyle: UIAlertControllerStyle.alert) //Replace UIAlertControllerStyle.Alert by UIAlertControllerStyle.alert

let DestructiveAction = UIAlertAction(title: "Destructive", style: UIAlertActionStyle.destructive) {
                        (result : UIAlertAction) -> Void in
    print("Destructive")
}

                    // Replace UIAlertActionStyle.Default by UIAlertActionStyle.default

let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
                        (result : UIAlertAction) -> Void in
    print("OK")
}

alertController.addAction(DestructiveAction)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)

See Alert With Destructive and OK Button:

enter image description here

Kirit Modi
  • 23,155
  • 15
  • 89
  • 112
  • what about action method?? does i need to mention seperate method for that?? – user5513630 Apr 04 '16 at 06:06
  • No Not.This is new in AlertController. And Button action event handle in this method. – Kirit Modi Apr 04 '16 at 06:07
  • for example when i press ok button i need to use this line `UIApplication.sharedApplication().openURL(NSURL(string: "prefs:root")!)` then where i can add this line in your code – user5513630 Apr 04 '16 at 06:09
  • instead of that `print("ok"), i need to add this line...Rignt?? – user5513630 Apr 04 '16 at 06:09
  • @KiritModi if we use UIAlertCOntroller instead of UIAlertView , then can we use this function "func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int){} " if not then what is the alternative? please help me , i am new – ArgaPK Nov 01 '17 at 06:35
  • @ArgaPK in the UIAlertCOntroller there are individual method of Buttons. So do the code in this button. you can see the OK button of above code. – Kirit Modi Nov 01 '17 at 06:43
  • @KiritModi you mean there is nothing like func alertView(alertView: UIAlertView, clickedButtonAtIndex bi: Int){} ?? if yes then how we write method? using UIAertAction?? Can we write this " if buttonIndex == 0 { //This will open ios devices wifi settings UIApplication.sharedApplication().openURL(NSURL(string: "prefs:root")!) } else if buttonIndex == 1 { //TODO for cancel exit(0) } " in UIALertAction of Button OK?? – ArgaPK Nov 01 '17 at 06:51
  • Remove the code and add code like: let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in UIApplication.sharedApplication().openURL(NSURL(string: "prefs:root")!) print("OK") } – Kirit Modi Nov 01 '17 at 06:55
  • @KiritModi ok let me try – ArgaPK Nov 01 '17 at 07:00
  • @KiritModi what does it mean " UIApplication.sharedApplication().openURL(NSURL(string: "prefs:root")!) " ? what will happen with this line of code? – ArgaPK Nov 01 '17 at 07:13
  • it's your reference so I added. – Kirit Modi Nov 01 '17 at 07:26
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/157973/discussion-between-argapk-and-kirit-modi). – ArgaPK Nov 01 '17 at 07:34
15

In Swift 3, you can write this:

let alertController = UIAlertController(title: "Title", message: "This is my text", preferredStyle: UIAlertControllerStyle.alert)

let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default)  
{ 
     (result : UIAlertAction) -> Void in
      print("You pressed OK")
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
ddb
  • 2,423
  • 7
  • 28
  • 38
Fred Sousa
  • 1,121
  • 13
  • 17
11

For a basic alert message I like using an extension on UIViewController:

extension UIViewController {
func alertMessageOk(title: String, message: String) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
   }
}

Usage: self.alertMessageOk(title: "Test Title", message: "Test message")

9BallOnTheSnap
  • 596
  • 6
  • 10
2

Swift 3

    // Create message
     let alertController = UIAlertController(title: "Title",
                                           message: "Message",
                                    preferredStyle: .actionSheet)

    // Clear Action
    let clearAction = UIAlertAction(title: "Clear",
                                    style: .destructive,
                                  handler: { (action:UIAlertAction!) in
                         print ("clear")
    })
    alertController.addAction(clearAction)

    // Cancel
    let cancelAction = UIAlertAction(title: "Cancel",
                                     style: .cancel,
                                   handler: { (action:UIAlertAction!) in
                                print ("Cancel")
    })
    alertController.addAction(cancelAction)

    // Present Alert
    self.present(alertController,
                 animated: true,
                 completion:nil)
Sébastien REMY
  • 2,399
  • 21
  • 39
1
  UIAlertController *AC = UIAlertController.alertControllerWithTitle("Title",message:"Message",preferredStyle:UIAlertControllerStyleAlert)

  UIAlertAction *ActionOne = [UIAlertAction actionWithTitle:"ActionOne" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { NSLog("ActionOne")
} ]

  UIAlertAction *ActionTwo = [UIAlertAction actionWithTitle:"ActionTwo" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { NSLog("ActionTwo")
} ]
AC.addAction(ActionOne)
AC.addAction(ActionTwo)
self.presentViewController(AC,animated:true,completion:nil)
Himanshu jamnani
  • 316
  • 2
  • 10
0

Try this code. Ex

 let actionSheetController: UIAlertController = UIAlertController(title: "Are you sure?", message: "", preferredStyle: .Alert)
 let cancelAction: UIAlertAction = UIAlertAction(title: "NO", style: .Cancel) { action -> Void in
                 //Do your task
  }
  actionSheetController.addAction(cancelAction)
  let nextAction: UIAlertAction = UIAlertAction(title: "YES", style: .Default) { action -> Void in
           //Do your task             //NSUserDefaults.standardUserDefaults().removePersistentDomainForName(NSBundle.mainBundle().bundleIdentifier!)
      //                  NSUserDefaults.standardUserDefaults().synchronize()
 }
 actionSheetController.addAction(nextAction)
 self.presentViewController(actionSheetController, animated: true, completion: nil)
Avijit Nagare
  • 8,482
  • 7
  • 39
  • 68
  • if we use UIAlertCOntroller instead of UIAlertView , then can we use this function "func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int){} " if not then what is the alternative? please help me , i am new – ArgaPK Nov 01 '17 at 06:36
  • @ArgaPK can you try Handler alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in println("Your code")})) – Avijit Nagare Nov 02 '17 at 09:40
0

This code will help

let alertController = UIAlertController(title: "Default AlertController", message: "A standard alert", preferredStyle: .Alert)

let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) 
{ 
   (action:UIAlertAction!) in
   print("you have pressed the Cancel button");
}
alertController.addAction(cancelAction)

let OKAction = UIAlertAction(title: "OK", style: .Default) 
{ 
  (action:UIAlertAction!) in
                print("you have pressed OK button");
}
alertController.addAction(OKAction)

self.presentViewController(alertController, animated: true, completion:nil)
Fred Sousa
  • 1,121
  • 13
  • 17
Govind Prajapati
  • 957
  • 7
  • 24
  • because i have set button click = 0,1 means i have set some action there know. so only asked – user5513630 Apr 04 '16 at 05:28
  • NO,you need to call your action method where i m printing (EX."you have pressed the Cancel button") when button pressed. You need to modify this code. – Govind Prajapati Apr 04 '16 at 05:35
  • Just replace that print statement to your method call.SIMPLE – Govind Prajapati Apr 04 '16 at 05:36
  • yes, i replace my action method call,Like `alertView` with the replacement of that print statement.But no action occur. does i am right to call that action method ?? – user5513630 Apr 04 '16 at 05:53
  • You are using old action's delegate method (and that method's parameters will be nil) so make new custom method with new name and then try to call it .It will definitely work. – Govind Prajapati Apr 04 '16 at 06:06
0

I have get this answer from this link i think it is useful to you

How to add an action to a UIAlertView button using Swift iOS

    var alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)

// Create the actions
var okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
    UIAlertAction in
    NSLog("OK Pressed")
}
var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
    UIAlertAction in
    NSLog("Cancel Pressed")
}

// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)

// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)
Community
  • 1
  • 1
Birendra
  • 623
  • 1
  • 5
  • 17