4

I am trying to present an alert using swift. This is the code I used from viewDidLoad but nothing happens when the code is run. Can someone help?

    var alert = UIAlertController(title: "test title",
        message: "test message",
        preferredStyle: .Alert)
    self.presentViewController(alert, animated: true, completion:nil)
user3764586
  • 125
  • 1
  • 2
  • 4
  • you can present a view controller in your view if your view has only been in the navigation stack already... – holex Jun 23 '14 at 10:14

2 Answers2

17

You must present any view controller after its parent view has been appeared . Put your presentation code to viewDidApear method.

override func viewDidAppear(animated: Bool)
    {
        super.viewDidAppear(animated)

        var alert = UIAlertController(title: "test title",
            message: "test message",
            preferredStyle: .alert)
        self.present(alert, animated: true, completion:nil)

    }
Mathieu Dutour
  • 549
  • 3
  • 13
Yatheesha
  • 10,412
  • 5
  • 42
  • 45
3

Show AlerView in swift for ios8

func showAlertVIew(){

        var alert = UIAlertController(title: "Info", message: "Welcome to Swift world.", preferredStyle: UIAlertControllerStyle.Alert)

        let alertOKAction=UIAlertAction(title:"OK", style: UIAlertActionStyle.Default,handler: { action in
            println("OK Button Pressed")
            })

        let alertCancelAction=UIAlertAction(title:"Cancel", style: UIAlertActionStyle.Destructive,handler: { action in
            println("Cancel Button Pressed")
         })

        alert.addAction(alertOKAction)
        alert.addAction(alertCancelAction)

        self.presentViewController(alert, animated: true, completion: nil)
    }
rsc
  • 10,348
  • 5
  • 39
  • 36