Create a simple Alert in swift

XCODE 10, IOS 12 And Swift 4 and above :

1. simple alert view with no action on buttons in an alert.

let alert = UIAlertController(title: "Error", message: "Something Went Wrong", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
self.present(alert, animated: true)

2. Alert with actions on ok and cancel button:

let refreshAlert = UIAlertController(title: "Punch Out", message: "You Will Will Punch Out", preferredStyle: UIAlertController.Style.alert)
        
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
            print("Handle Ok logic here")
   }))
        
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
            print("Handle Cancel Logic here")
            refreshAlert .dismiss(animated: true, completion: nil)
   }))

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

For more customization Refer to this StackOverflow Answer


Try with following code

let alert = UIAlertView()
alert.title = "Title"
alert.message = "My message"
alert.addButtonWithTitle("Ok")
alert.show()

But in iOS 8

UIAlertView is deprecated. So use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert. it should be

var alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)