UIAlertController not being shown - ios

this is my ViewController.swift:
import Intents
class ViewController: UIViewController {
#IBAction func getdbb() {
db().getdb { (Db) in
let alert1 = UIAlertController (title: "Random Trivia", message : Db, preferredStyle: .alert)
alert1.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
let alert2 = UIAlertController(title: nil, message: "Do you want to go to the next question?", preferredStyle: .alert)
alert2.addAction(UIAlertAction(title: "YES", style: .default, handler:{ action in self.getdbb() }))
alert2.addAction(UIAlertAction(title :"NO", style: .default, handler: nil ))
}))
self.present(alert1, animated: true, completion: nil)
INInteraction(intent: GetQuestionIntent(), response: nil).donate(completion: nil)
}
}
}
and I have a query button in my main.storyboard which is connected to the getdbb function, yet the alert UI is not shown in the simulator. This is what happens when I click the query button (output is only shown in Xcode):

You are not presenting the controller in the Main Thread, so try as below:
db().getdb { (Db) in
DispatchQueue.main.async {
let alert1 = UIAlertController (title: "Random Trivia", message : Db, preferredStyle: .alert)
alert1.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
let alert2 = UIAlertController(title: nil, message: "Do you want to go to the next question?", preferredStyle: .alert)
alert2.addAction(UIAlertAction(title: "YES", style: .default, handler:{ action in self.getdbb() }))
alert2.addAction(UIAlertAction(title :"NO", style: .default, handler: nil ))
}))
self.present(alert1, animated: true, completion: nil)
INInteraction(intent: GetQuestionIntent(), response: nil).donate(completion: nil)
}
}

Related

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

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!
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:
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)
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")
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)
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)
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)
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)
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)

iOS 9, Swift 2.1 - Delete alert in vertical layout

I have a plain style alert that shows 2 buttons horizontally made with the following implementation and I'd like to know how I can make it like the attached image.
let alert = UIAlertController(title: "", message: "This item will be deleted", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil));
alert.addAction(UIAlertAction(title: "Delete", style: UIAlertActionStyle.Destructive, handler: {
alertAction in
self.deleteItem(sender)
}))
presentViewController(alert, animated: true, completion: nil);
Use this one :-
let alert = UIAlertController(title: "", message: "This item will be deleted", preferredStyle: .ActionSheet)
You can use the following for what u want to acheive
#IBAction func actionRecommend(sender: UIButton) {
let optionMenu = UIAlertController(title: nil, message: "Recommend Using", preferredStyle: .ActionSheet)
optionMenu.view.tintColor = primaryDarkColor
let deleteAction = UIAlertAction(title: "Facebook", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
print("File Facebook")
})
let saveAction = UIAlertAction(title: "Contacts", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
print("File toContacts")
// self.performSegueWithIdentifier("toContacts", sender: nil)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancelled")
})
optionMenu.addAction(deleteAction)
optionMenu.addAction(saveAction)
optionMenu.addAction(cancelAction)
self.presentViewController(optionMenu, animated: true, completion: nil)
}

How to present iOS UIActionSheet in Swift?

How can I present a UIActionSheet in Swift within an iOS app?
Here is my code for displaying a UIActionSheet:
#IBAction func downloadSheet(sender: AnyObject) {
let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)
let saveAction = UIAlertAction(title: "Save", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
println("Saved")
})
let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
println("Deleted")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
println("Cancelled")
})
optionMenu.addAction(deleteAction)
optionMenu.addAction(saveAction)
optionMenu.addAction(cancelAction)
self.presentViewController(optionMenu, animated: true, completion: nil)
}
Updated for Swift 4/5
Works for iOS 11-14
Some of the other answers are okay but I ended up mixing and matching a few of them to rather come up with this :
#IBAction func showAlert(sender: AnyObject) {
let alert = UIAlertController(title: "Title", message: "Please Select an Option", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (UIAlertAction)in
print("User click Approve button")
}))
alert.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (UIAlertAction)in
print("User click Edit button")
}))
alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
print("User click Delete button")
}))
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler:{ (UIAlertAction)in
print("User click Dismiss button")
}))
//uncomment for iPad Support
//alert.popoverPresentationController?.sourceView = self.view
self.present(alert, animated: true, completion: {
print("completion block")
})
}
Enjoy :)
Your Approach is fine, but you can add UIActionSheet with other way with ease.
You can add UIActionSheetDelegate in UIViewController` like
class ViewController: UIViewController ,UIActionSheetDelegate
Set you method like,
#IBAction func downloadSheet(sender: AnyObject)
{
let actionSheet = UIActionSheet(title: "Choose Option", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: "Save", "Delete")
actionSheet.showInView(self.view)
}
You can get your button index when it clicked like
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int)
{
println("\(buttonIndex)")
switch (buttonIndex){
case 0:
println("Cancel")
case 1:
println("Save")
case 2:
println("Delete")
default:
println("Default")
//Some code here..
}
}
Update 1: for iOS8+
//Create the AlertController and add Its action like button in Actionsheet
let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: "Please select", message: "Option to select", preferredStyle: .ActionSheet)
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { _ in
print("Cancel")
}
actionSheetControllerIOS8.addAction(cancelActionButton)
let saveActionButton = UIAlertAction(title: "Save", style: .default)
{ _ in
print("Save")
}
actionSheetControllerIOS8.addAction(saveActionButton)
let deleteActionButton = UIAlertAction(title: "Delete", style: .default)
{ _ in
print("Delete")
}
actionSheetControllerIOS8.addAction(deleteActionButton)
self.present(actionSheetControllerIOS8, animated: true, completion: nil)
UIActionSheet is deprecated in iOS 8.
I am using following:
// Create the AlertController
let actionSheetController = UIAlertController(title: "Please select", message: "How you would like to utilize the app?", preferredStyle: .ActionSheet)
// Create and add the Cancel action
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
// Just dismiss the action sheet
}
actionSheetController.addAction(cancelAction)
// Create and add first option action
let takePictureAction = UIAlertAction(title: "Consumer", style: .Default) { action -> Void in
self.performSegueWithIdentifier("segue_setup_customer", sender: self)
}
actionSheetController.addAction(takePictureAction)
// Create and add a second option action
let choosePictureAction = UIAlertAction(title: "Service provider", style: .Default) { action -> Void in
self.performSegueWithIdentifier("segue_setup_provider", sender: self)
}
actionSheetController.addAction(choosePictureAction)
// We need to provide a popover sourceView when using it on iPad
actionSheetController.popoverPresentationController?.sourceView = sender as UIView
// Present the AlertController
self.presentViewController(actionSheetController, animated: true, completion: nil)
Updated for Swift 3.x, Swift 4.x, Swift 5.x
// create an actionSheet
let actionSheetController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// create an action
let firstAction: UIAlertAction = UIAlertAction(title: "First Action", style: .default) { action -> Void in
print("First Action pressed")
}
let secondAction: UIAlertAction = UIAlertAction(title: "Second Action", style: .default) { action -> Void in
print("Second Action pressed")
}
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in }
// add actions
actionSheetController.addAction(firstAction)
actionSheetController.addAction(secondAction)
actionSheetController.addAction(cancelAction)
// present an actionSheet...
// present(actionSheetController, animated: true, completion: nil) // doesn't work for iPad
actionSheetController.popoverPresentationController?.sourceView = yourSourceViewName // works for both iPhone & iPad
present(actionSheetController, animated: true) {
print("option menu presented")
}
Update for Swift 3:
// Create the AlertController and add its actions like button in ActionSheet
let actionSheetController = UIAlertController(title: "Please select", message: "Option to select", preferredStyle: .actionSheet)
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
let saveActionButton = UIAlertAction(title: "Save", style: .default) { action -> Void in
print("Save")
}
actionSheetController.addAction(saveActionButton)
let deleteActionButton = UIAlertAction(title: "Delete", style: .default) { action -> Void in
print("Delete")
}
actionSheetController.addAction(deleteActionButton)
self.present(actionSheetController, animated: true, completion: nil)
Generetic Action Sheet working for Swift 4, 4.2, 5
If you like a generic version that you can call from every ViewController and in every project try this one:
class Alerts {
static func showActionsheet(viewController: UIViewController, title: String, message: String, actions: [(String, UIAlertActionStyle)], completion: #escaping (_ index: Int) -> Void) {
let alertViewController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
for (index, (title, style)) in actions.enumerated() {
let alertAction = UIAlertAction(title: title, style: style) { (_) in
completion(index)
}
alertViewController.addAction(alertAction)
}
// iPad Support
alertViewController.popoverPresentationController?.sourceView = viewController.view
viewController.present(alertViewController, animated: true, completion: nil)
}
}
Call like this in your ViewController.
var actions: [(String, UIAlertActionStyle)] = []
actions.append(("Action 1", UIAlertActionStyle.default))
actions.append(("Action 2", UIAlertActionStyle.destructive))
actions.append(("Action 3", UIAlertActionStyle.cancel))
//self = ViewController
Alerts.showActionsheet(viewController: self, title: "D_My ActionTitle", message: "General Message in Action Sheet", actions: actions) { (index) in
print("call action \(index)")
/*
results
call action 0
call action 1
call action 2
*/
}
Attention: Maybe you're wondering why I add Action 1/2/3 but got results like 0,1,2. In the line for (index, (title, style)) in actions.enumerated() I get the index of actions. Arrays always begin with the index 0. So the completion is 0,1,2.
If you like to set a enum, an id or another identifier I would recommend to hand over an object in parameter actions.
Action Sheet in iOS10 with Swift3.0. Follow this link.
#IBAction func ShowActionSheet(_ sender: UIButton) {
// Create An UIAlertController with Action Sheet
let optionMenuController = UIAlertController(title: nil, message: "Choose Option from Action Sheet", preferredStyle: .actionSheet)
// Create UIAlertAction for UIAlertController
let addAction = UIAlertAction(title: "Add", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Add")
})
let saveAction = UIAlertAction(title: "Edit", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Edit")
})
let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Delete")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancel")
})
// Add UIAlertAction in UIAlertController
optionMenuController.addAction(addAction)
optionMenuController.addAction(saveAction)
optionMenuController.addAction(deleteAction)
optionMenuController.addAction(cancelAction)
// Present UIAlertController with Action Sheet
self.present(optionMenuController, animated: true, completion: nil)
}
2022 Swift 5
func yourActionSheet() -> UIAlertController {
let alert = UIAlertController(title: "Your title",
message: nil,
preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Your action 1",
style: .default) { _ in
// onAction1()
})
alert.addAction(UIAlertAction(title: "Your action 2",
style: .default) { _ in
// onAction2()
})
alert.addAction(UIAlertAction(title: "Your cancel action",
style: .cancel) { _ in
// onCancel
})
return alert
}
SWIFT 4
WORKS ON IPHONE AND IPAD BOTH. ALSO ALLOWS ROTATION
LANDSCAPE
PORTRAIT
Code (tested)
let alert = UIAlertController()
let width: Int = Int(UIScreen.main.bounds.width - 100)
let viewAction = UIAlertAction(title: "View", style: .default , handler:{ (UIAlertAction)in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let orderDetailVC = storyboard.instantiateViewController(withIdentifier: "orderDetail") as! OrderDetailTableViewController
orderDetailVC.orderId = self.myDraftOrders[indexPath.row]["id"].intValue
self.navigationController?.pushViewController(orderDetailVC, animated: true)
})
viewAction.setValue(appGreenColor, forKey: "titleTextColor")
alert.addAction(viewAction)
let modifyAction = UIAlertAction(title: "Modify", style: .default, handler:{ (UIAlertAction)in
showAlert("Coming soon...")
})
modifyAction.setValue(appCyanColor, forKey: "titleTextColor")
alert.addAction(modifyAction)
let copyAction = UIAlertAction(title: "Copy", style: .default, handler:{ (UIAlertAction)in
self.copyOrder(orderId: self.myDraftOrders[indexPath.row]["id"].intValue)
})
copyAction.setValue(appBlueColor, forKey: "titleTextColor")
alert.addAction(copyAction)
alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
self.deleteOrder(orderId: self.myDraftOrders[indexPath.row]["id"].intValue, indexPath: indexPath)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction)in
print("User click Dismiss button")
}))
let popover = alert.popoverPresentationController
popover?.delegate = self
let cellT = tableView.cellForRow(at: indexPath)
popover?.sourceView = cellT
popover?.sourceRect = CGRect(x: width, y: 25, width: 100, height: 50)
present(alert, animated: true)
Swift :
The sample code given below works both on iPhone and iPad.
guard let viewRect = sender as? UIView else {
return
}
let cameraSettingsAlert = UIAlertController(title: NSLocalizedString("Please choose a course", comment: ""), message: NSLocalizedString("", comment: ""), preferredStyle: .ActionSheet)
cameraSettingsAlert.modalPresentationStyle = .Popover
let photoResolutionAction = UIAlertAction(title: NSLocalizedString("Photo Resolution", comment: ""), style: .Default) { action in
}
let cameraOrientationAction = UIAlertAction(title: NSLocalizedString("Camera Orientation", comment: ""), style: .Default) { action in
}
let flashModeAction = UIAlertAction(title: NSLocalizedString("Flash Mode", comment: ""), style: .Default) { action in
}
let timeStampOnPhotoAction = UIAlertAction(title: NSLocalizedString("Time Stamp on Photo", comment: ""), style: .Default) { action in
}
let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action in
}
cameraSettingsAlert.addAction(cancel)
cameraSettingsAlert.addAction(cameraOrientationAction)
cameraSettingsAlert.addAction(flashModeAction)
cameraSettingsAlert.addAction(timeStampOnPhotoAction)
cameraSettingsAlert.addAction(photoResolutionAction)
if let presenter = cameraSettingsAlert.popoverPresentationController {
presenter.sourceView = viewRect;
presenter.sourceRect = viewRect.bounds;
}
presentViewController(cameraSettingsAlert, animated: true, completion: nil)
The Old Way: UIActionSheet
let actionSheet = UIActionSheet(title: "Takes the appearance of the bottom bar if specified; otherwise, same as UIActionSheetStyleDefault.", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: "Destroy", otherButtonTitles: "OK")
actionSheet.actionSheetStyle = .Default
actionSheet.showInView(self.view)
// MARK: UIActionSheetDelegate
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
...
}
}
The New Way: UIAlertController
let alertController = UIAlertController(title: nil, message: "Takes the appearance of the bottom bar if specified; otherwise, same as UIActionSheetStyleDefault.", preferredStyle: .ActionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
let destroyAction = UIAlertAction(title: "Destroy", style: .Destructive) { (action) in
println(action)
}
alertController.addAction(destroyAction)
self.presentViewController(alertController, animated: true) {
// ...
}
Swift 3
For displaying UIAlertController from UIBarButtonItem on iPad
let alert = UIAlertController(title: "Title", message: "Please Select an Option", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (UIAlertAction)in
print("User click Approve button")
}))
alert.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (UIAlertAction)in
print("User click Edit button")
}))
alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
print("User click Delete button")
}))
alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.cancel, handler:{ (UIAlertAction)in
print("User click Dismiss button")
}))
if let presenter = alert.popoverPresentationController {
presenter.barButtonItem = sender
}
self.present(alert, animated: true, completion: {
print("completion block")
})
swift4 (tested)
let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .actionSheet)
let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
print("Default is pressed.....")
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
print("Cancel is pressed......")
}
let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
print("Destructive is pressed....")
}
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
self.present(alertController, animated: true, completion: nil)
}
Code for adding alerts to actionsheet in swift4
*That means when we click actionsheet values(like edit/ delete..so on) it shows
an alert option that is set with Yes or No option*
class ViewController: UIViewController
{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func action_sheet1(_ sender: Any) {
let action_sheet1 = UIAlertController(title: "Hi Bro", message: "Please Select an Option: ", preferredStyle: .actionSheet)
action_sheet1.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
print("User click Approve button")
let alert = UIAlertController(title: "Approve", message: "Would you like to approve the file ", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
action_sheet1.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
print("User click Edit button")
let alert = UIAlertController(title: "Edit", message: "Would you like to edit the file ", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
action_sheet1.addAction(UIAlertAction(title: "Delete", style: .destructive , handler: { (alert: UIAlertAction!) -> Void in
print("User click Delete button")
let alert = UIAlertController(title: "Delete", message: "Would you like to delete the file permenently?", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
action_sheet1.addAction(UIAlertAction(title: "cancel", style: .cancel, handler:{ (alert: UIAlertAction!) -> Void in
print("User click cancel button")
let alert = UIAlertController(title: "Cancel", message: "Would you like to cancel?", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
self.present(action_sheet1, animated: true, completion: {
print("completion block")
})
}
}
Useful to populate dynamic actions list, and listen to selected action:
var categories = ["Science", "History", "Industry", "Agriculture"]
var handlerSelectedCategory: ((Int) -> ())?
func prepareActions(for title: String, index: Int) -> UIAlertAction {
let alertAction = UIAlertAction(title: title, style: .default) { (action) in
self.handlerSelectedCategory?(index)
}
return alertAction
}
#objc func presentActions() {
let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// add dymamic options
for (index, element) in self.categories.enumerated() {
optionMenu.addAction(prepareActions(for: element, index: index))
}
// cancel
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive)
optionMenu.addAction(cancelAction)
handlerSelectedCategory = { index in
print(index, self.categories[index])
}
self.present(optionMenu, animated: true, completion: nil)
}
You can use following code for Alert and ActionSheet in Swift 4:
#IBAction func alert_act(_ sender: Any) {
do {
let alert = UIAlertController(title: "Alert", message: "Would you like to continue learning?", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
#IBAction func action_sheet1(_ sender: Any) {
let action_sheet1 = UIAlertController(title: nil, message: "Alert message.", preferredStyle: .actionSheet)
let defaultAction = UIAlertAction(title: "Default", style: .default, handler: nil)
let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
action_sheet1.addAction(defaultAction)
action_sheet1.addAction(deleteAction)
action_sheet1.addAction(cancelAction)
self.present(action_sheet1, animated: true, completion: nil)
}
Swift 5+
Very Simple and Smooth way just call this function and Boommmmmm!!!!!!!
let IPAD = UIDevice.current.userInterfaceIdiom == .pad
//Mark:- Choose Image Method
func funcMyActionSheet() {
var myActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
myActionSheet.view.tintColor = UIColor.black
let galleryAction = UIAlertAction(title: "Gallery".localizableString(language: Defaults.selectedLanguageCode), style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.openGallary()
})
let cmaeraAction = UIAlertAction(title: "Camera".localizableString(language: Defaults.selectedLanguageCode), style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.openCamera()
})
let cancelAction = UIAlertAction(title: "Cancel".localizableString(language: Defaults.selectedLanguageCode), style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
})
if IPAD {
//In iPad Change Rect to position Popover
myActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.alert)
}
myActionSheet.addAction(galleryAction)
myActionSheet.addAction(cmaeraAction)
myActionSheet.addAction(cancelAction)
print("Action Sheet call")
self.present(myActionSheet, animated: true, completion: nil)
}
You can use following code for open actionSheet in Swift:
let alert = UIAlertController(title: enter your title, message: "Enter your messgage. ", preferredStyle: UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler(configurationTextField)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:{ (UIAlertAction)in
print("User click Cancel button")
}))
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
print("User click Ok button")
}))
self.presentViewController(alert, animated: true, completion: {
print("completion block")
})

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

I want to add another button other than the "OK" button which should just dismiss the alert.
I want the other button to call a certain function.
var logInErrorAlert: UIAlertView = UIAlertView()
logInErrorAlert.title = "Ooops"
logInErrorAlert.message = "Unable to log in."
logInErrorAlert.addButtonWithTitle("Ok")
How do I add another button to this alert, and then allow it to call a function once clicks so lets say we want the new button to call:
retry()
The Swifty way is to use the new UIAlertController and closures:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
}
let 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)
Swift 3:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
let 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.present(alertController, animated: true, completion: nil)
func showAlertAction(title: String, message: String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
print("Action")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
UIAlertViews use a delegate to communicate with you, the client.
You add a second button, and you create an object to receive the delegate messages from the view:
class LogInErrorDelegate : UIAlertViewDelegate {
init {}
// not sure of the prototype of this, you should look it up
func alertView(view :UIAlertView, clickedButtonAtIndex :Integer) -> Void {
switch clickedButtonAtIndex {
case 0:
userClickedOK() // er something
case 1:
userClickedRetry()
/* Don't use "retry" as a function name, it's a reserved word */
default:
userClickedRetry()
}
}
/* implement rest of the delegate */
}
logInErrorAlert.addButtonWithTitle("Retry")
var myErrorDelegate = LogInErrorDelegate()
logInErrorAlert.delegate = myErrorDelegate
Swift 5+
let alert = UIAlertController(title: "Cart!", message: "Are you sure want to remove order details?", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "YES", style:
UIAlertAction.Style.default) {
UIAlertAction in
print("Yes Pressed")
}
let cancelAction = UIAlertAction(title: "CANCEL", style:
UIAlertAction.Style.cancel) {
UIAlertAction in
print("Cancel Pressed")
}
// Add the actions
alert.addAction(okAction)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
OR
let alert = UIAlertController(title: "Alert!", message: "Are you sure want to remove your request?", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "YES", style: .destructive) {
_ in
print("Yes Pressed")
self.funRemoveRequest(requestID: (self.requestStatusModel?.data?[sender.tag].id)!)
}
let cancelAction = UIAlertAction(title: "CANCEL", style: .cancel) {
_ in
print("Cancel Pressed")
}
// Add the actions
alert.addAction(okAction)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
Swift 4 Update
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
let 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.present(alertController, animated: true, completion: nil)
based on swift:
let alertCtr = UIAlertController(title:"Title", message:"Message", preferredStyle: .Alert)
let Cancel = AlertAction(title:"remove", style: .Default, handler: {(UIAlertAction) -> Void in })
let Remove = UIAlertAction(title:"remove", style: .Destructive, handler:{(UIAlertAction)-> Void
inself.colorLabel.hidden = true
})
alertCtr.addAction(Cancel)
alertCtr.addAction(Remove)
self.presentViewController(alertCtr, animated:true, completion:nil)}
Swift 3.0 Version of Jake's Answer
// Create the alert controller
let alertController = UIAlertController(title: "Alert!", message: "There is no items for the current user", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
let 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.present(alertController, animated: true, completion: nil)
See my code:
#IBAction func foundclicked(sender: AnyObject) {
if (amountTF.text.isEmpty)
{
let alert = UIAlertView(title: "Oops! Empty Field", message: "Please enter the amount", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
else {
var alertController = UIAlertController(title: "Confirm Bid Amount", message: "Final Bid Amount : "+amountTF.text , preferredStyle: .Alert)
var okAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.Default) {
UIAlertAction in
JHProgressHUD.sharedHUD.loaderColor = UIColor.redColor()
JHProgressHUD.sharedHUD.showInView(self.view, withHeader: "Amount registering" , andFooter: "Loading")
}
var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
alertController .removeFromParentViewController()
}
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
this is for swift 4.2, 5 and 5+
let alert = UIAlertController(title: "ooops!", message: "Unable to login", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)

How would I create a UIAlertView in Swift?

I have been working to create a UIAlertView in Swift, but for some reason I can't get the statement right because I'm getting this error:
Could not find an overload for 'init' that accepts the supplied
arguments
Here is how I have it written:
let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)
Then to call it I'm using:
button2Alert.show()
As of right now it is crashing and I just can't seem to get the syntax right.
From the UIAlertView class:
// UIAlertView is deprecated. Use UIAlertController with a
preferredStyle of UIAlertControllerStyleAlert instead
On iOS 8, you can do this:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
Now UIAlertController is a single class for creating and interacting with what we knew as UIAlertViews and UIActionSheets on iOS 8.
Edit: To handle actions:
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
switch action.style{
case .Default:
print("default")
case .Cancel:
print("cancel")
case .Destructive:
print("destructive")
}
}}))
Edit for Swift 3:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
Edit for Swift 4.x:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}
}))
self.present(alert, animated: true, completion: nil)
One Button
class ViewController: UIViewController {
#IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Two Buttons
class ViewController: UIViewController {
#IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "UIAlertController", message: "Would you like to continue learning how to use iOS alerts?", preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Three Buttons
class ViewController: UIViewController {
#IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "Notice", message: "Lauching this missile will destroy the entire universe. Is this what you intended to do?", preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Remind Me Tomorrow", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
Handling Button Taps
The handler was nil in the above examples. You can replace nil with a closure to do something when the user taps a button. For example:
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: { action in
// do something like...
self.launchMissile()
}))
Notes
Multiple buttons do not necessarily need to use different UIAlertAction.Style types. They could all be .default.
For more than three buttons consider using an Action Sheet. The setup is very similar. Here is an example.
You can create a UIAlert using the standard constructor, but the 'legacy' one seems to not work:
let alert = UIAlertView()
alert.title = "Alert"
alert.message = "Here's a message"
alert.addButtonWithTitle("Understood")
alert.show()
In Swift 4.2 and Xcode 10
Method 1 :
SIMPLE ALERT
let alert = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(ok)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
Method 2 :
ALERT WITH SHARED CLASS
If you want Shared class style(Write once use every where)
import UIKit
class SharedClass: NSObject {//This is shared class
static let sharedInstance = SharedClass()
//Show alert
func alert(view: UIViewController, title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(defaultAction)
DispatchQueue.main.async(execute: {
view.present(alert, animated: true)
})
}
private override init() {
}
}
Now call alert like this in every ware
SharedClass.sharedInstance.alert(view: self, title: "Your title here", message: "Your message here")
Method 3 :
PRESENT ALERT TOP OF ALL WINDOWS
If you want to present alert on top of all views, use this code
func alertWindow(title: String, message: String) {
DispatchQueue.main.async(execute: {
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1
let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert2.addAction(defaultAction2)
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)
})
}
Function calling
SharedClass.sharedInstance.alertWindow(title:"This your title", message:"This is your message")
Method 4 :
Alert with Extension
extension UIViewController {
func showAlert(withTitle title: String, withMessage message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(ok)
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
}
}
Now call like this
//Call showAlert function in your class
#IBAction func onClickAlert(_ sender: UIButton) {
showAlert(withTitle:"Your Title Here", withMessage: "YourCustomMessageHere")
}
Method 5 :
ALERT WITH TEXTFIELDS
If you want to add textfields to alert.
//Global variables
var name:String?
var login:String?
//Call this function like this: alertWithTF()
//Add textfields to alert
func alertWithTF() {
let alert = UIAlertController(title: "Login", message: "Enter username&password", preferredStyle: .alert)
// Login button
let loginAction = UIAlertAction(title: "Login", style: .default, handler: { (action) -> Void in
// Get TextFields text
let usernameTxt = alert.textFields![0]
let passwordTxt = alert.textFields![1]
//Asign textfileds text to our global varibles
self.name = usernameTxt.text
self.login = passwordTxt.text
print("USERNAME: \(self.name!)\nPASSWORD: \(self.login!)")
})
// Cancel button
let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) -> Void in })
//1 textField for username
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter username"
//If required mention keyboard type, delegates, text sixe and font etc...
//EX:
textField.keyboardType = .default
}
//2nd textField for password
alert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter password"
textField.isSecureTextEntry = true
}
// Add actions
alert.addAction(loginAction)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
Method 6:
Alert in SharedClass with Extension
//This is your shared class
import UIKit
class SharedClass: NSObject {
static let sharedInstance = SharedClass()
//Here write your code....
private override init() {
}
}
//Alert function in shared class
extension UIViewController {
func showAlert(title: String, msg: String) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
Now call directly like this
self.showAlert(title: "Your title here...", msg: "Your message here...")
Method 7:
Alert with out shared class with Extension in separate class for alert.
Create one new Swift class, and import UIKit. Copy and paste below code.
//This is your Swift new class file
import UIKit
import Foundation
extension UIAlertController {
class func alert(title:String, msg:String, target: UIViewController) {
let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default) {
(result: UIAlertAction) -> Void in
})
target.present(alert, animated: true, completion: nil)
}
}
Now call alert function like this in all your classes (Single line).
UIAlertController.alert(title:"Title", msg:"Message", target: self)
How is it....
Click of View
#IBAction func testClick(sender: UIButton) {
var uiAlert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(uiAlert, animated: true, completion: nil)
uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
println("Click of default button")
}))
uiAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
println("Click of cancel button")
}))
}
Done with two buttons OK & Cancel
If you're targeting iOS 7 and 8, you need something like this to make sure you're using the right method for each version, because UIAlertView is deprecated in iOS 8, but UIAlertController is not available in iOS 7:
func alert(title: String, message: String) {
if let getModernAlert: AnyClass = NSClassFromString("UIAlertController") { // iOS 8
let myAlert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
myAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(myAlert, animated: true, completion: nil)
} else { // iOS 7
let alert: UIAlertView = UIAlertView()
alert.delegate = self
alert.title = title
alert.message = message
alert.addButtonWithTitle("OK")
alert.show()
}
}
With the protocol extensions of Swift 2, you can make a protocol that provides a default implementation to your view controllers:
ShowsAlert.swift
import UIKit
protocol ShowsAlert {}
extension ShowsAlert where Self: UIViewController {
func showAlert(title: String = "Error", message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
}
}
ViewController.swift
class ViewController: UIViewController, ShowsAlert {
override func viewDidLoad() {
super.viewDidLoad()
showAlert(message: "Hey there, I am an error message!")
}
}
Show UIAlertView in swift language :-
Protocol UIAlertViewDelegate
let alert = UIAlertView(title: "alertView", message: "This is alertView", delegate:self, cancelButtonTitle:"Cancel", otherButtonTitles: "Done", "Delete")
alert.show()
Show UIAlertViewController in swift language :-
let alert = UIAlertController(title: "Error", message: "Enter data in Text fields", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
Simply do not provide otherButtonTitles in the constructor.
let alertView = UIAlertView(title: "Oops!", message: "Something
happened...", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
But I do agree with Oscar, this class is deprecated in iOS 8, so there won't be no use of UIAlertView if you're doing an iOS 8 only app. Otherwise the code above will work.
For SWIFT4, I think, extending UIViewController and creating a reusable confirmation control is the most elegant way.
You can extend the UIViewController as below:
extension UIViewController {
func AskConfirmation (title:String, message:String, completion:#escaping (_ result:Bool) -> Void) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true, completion: nil)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
completion(true)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
completion(false)
}))
}
}
Then you can use it anytime:
AskConfirmation(title: "YOUR MESSAGE TITLE", message: "YOUR MESSAGE") { (result) in
if result { //User has clicked on Ok
} else { //User has clicked on Cancel
}
}
AlertView Swift 5 and above:-
let alert = UIAlertController(title: LocalizedStringConstant.alert, message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Retry", style: .cancel, handler: { (_) in
}))
self.present(alert, animated: true, completion: nil)
I found this one,
var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();
not good though, but it works :)
Update:
but I have found on header file as:
extension UIAlertView {
convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
}
somebody may can explain this.
For iOS 13 Xcode 11+ Swift 5.X
UIAlertController can now provide Alerts as well as Action Sheets
Alerts
// First instantiate the UIAlertController
let alert = UIAlertController(title: "Title",
message: "Message ?",
preferredStyle: .alert)
// Add action buttons to it and attach handler functions if you want to
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Just Do It!", style: .destructive, handler: nil))
alert.addAction(UIAlertAction(title: "Maybe", style: .default, handler: nil))
// Show the alert by presenting it
self.present(alert, animated: true)
Note that it's is a fundamental nature for all action buttons to dismiss the alert view when tapped. The style parameter is just for deciding the color of the text (and some default order in which the buttons should appear which ofc can be changed)
A sample handler function could be
func handler(_ action: UIAlertAction) {
if action.title == 'Title' {
// do stuff
}
}
As a side note, I would say instead of making 3 different handlers you can just make 1 and trace back to the element which provoked it in the manner shown above
We can also check alert.style but that again we can have multiple .default styled actions , I wouldn't recommend that
Action Sheets
The explanation is similar because the main difference here is that an alert interrupts the user whereas an action sheet slides from the bottom in an iPhone and appears as a popover in an iPad
The Purpose of action sheets is to guide the users in deciding his actions based on their current state. So you gotta treat action sheets like crossroads !. There is generally no message and the title is rendered as caption sized text
let action = UIAlertController(title: "What do you want to do with the message",
message: nil,
preferredStyle: .actionSheet)
action.addAction(UIAlertAction(title: "Cancel", style: .cancel))
for act in ["Save", "Post", "Discard"] {
action.addAction(UIAlertAction(title: act, style: .default, handler: nil))
}
self.present(action, animated: true)
The above code is going to work for an iPhone but will crash at runtime for an iPad because UIPopoverPresentationController is going to take charge of the alert and it won't be referencing anything at that time. So to avoid that you will have to provide the following chunk of code its mandatory
if let pop = action.popoverPresentationController {
let v = sender as! UIView
pop.sourceView = v
pop.sourceRect = v.bounds
}
Also in case of iPad tapping on anywhere outside the popover will dismiss it and the completion handler of .cancel action button will be called.
Hope that helps :) That being said, comment down below if you have any doubts
class Preview: UIViewController , UIAlertViewDelegate
{
#IBAction func MoreBtnClicked(sender: AnyObject)
{
var moreAlert=UIAlertView(title: "Photo", message: "", delegate: self, cancelButtonTitle: "No Thanks!", otherButtonTitles: "Save Image", "Email", "Facebook", "Whatsapp" )
moreAlert.show()
moreAlert.tag=111;
}
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int)
{
if alertView.tag==111
{
if buttonIndex==0
{
println("No Thanks!")
}
else if buttonIndex==1
{
println("Save Image")
}
else if buttonIndex == 2
{
println("Email")
}
else if buttonIndex == 3
{
println("Facebook")
}
else if buttonIndex == 4
{
println("Whatsapp")
}
}
}
}
I have another trick. Suppose you have 5 classes where a logout alert to be applied. Try with swift class extension.
File- New- Swift class- Name it.
Add the following:
public extension UIViewController
{
func makeLogOutAlert()
{
var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
self.navigationController?.popToRootViewControllerAnimated(true)
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
refreshAlert .dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(refreshAlert, animated: true, completion: nil)
}
}
Implement using : self.makeLogOutAlert(). Hope it helps.
I have made a singleton class to make this convenient to use from anywhere in your app: https://github.com/Swinny1989/Swift-Popups
You can then create a popup with multiple buttons like this:
Popups.SharedInstance.ShowAlert(self, title: "Title goes here", message: "Messages goes here", buttons: ["button one" , "button two"]) { (buttonPressed) -> Void in
if buttonPressed == "button one" {
//Code here
} else if buttonPressed == "button two" {
// Code here
}
}
or popups with a single button like this:
Popups.SharedInstance.ShowPopup("Title goes here", message: "Message goes here.")
Swift 3
The following is a simple example of how to create a simple alert with one button with Swift 3.
let alert = UIAlertController(title: "Title",
message: "Message",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true)
In the above example the handle callback of the action has been omitted because the default behaviour of an alert view with one button is to disappear when the button is clicked.
Here is how to create another action, which could be added to the alert with "alert.addAction(action)". The different styles are .default, .destructive and .cancel.
let action = UIAlertAction(title: "Ok", style: .default) { action in
// Handle when button is clicked
}
I got the following UIAlertView initialization code to compile without errors (I thing the last, varyadic part is tricky perhaps). But I had to make sure the class of self (which I am passing as the delegate) was adopting the UIAlertViewDelegate protocol for the compile errors to go away:
let alertView = UIAlertView(
title: "My Title",
message: "My Message",
delegate: self,
cancelButtonTitle: "Cancel",
otherButtonTitles: "OK"
)
By the way, this is the error I was getting (as of Xcode 6.4):
Cannot find an initializer for type 'UIAlertView' that accepts an
argument list of type '(title: String, message: String, delegate:
MyViewController, cancelButtonTitle: String, otherButtonTitles:
String)'
As others mentioned, you should migrate to UIAlertController if you can target iOS 8.x+. To support iOS 7, use the code above (iOS 6 is not supported by Swift).
let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .alert)
let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
print("Default is pressed.....")
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
print("Cancel is pressed......")
}
let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
print("Destructive is pressed....")
}
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
self.present(alertController, animated: true, completion: nil)
}
You can use this simple extension with n number of buttons and associated actions swift4 and above
extension UIViewController {
func popupAlert(title: String?, message: String?, actionTitles:[String?], actions:[((UIAlertAction) -> Void)?]) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
for (index, title) in actionTitles.enumerated() {
let action = UIAlertAction(title: title, style: .default, handler: actions[index])
alert.addAction(action)
}
self.present(alert, animated: true, completion: nil)
}
}
you can use it like ,
self.popupAlert(title: "Message", message: "your message", actionTitles: ["first","second","third"], actions:[
{action1 in
//action for first btn click
},
{action2 in
//action for second btn click
},
{action3 in
//action for third btn click
}, nil])
The reason it doesn't work because some value you passed to the function isn't correct. swift doesn't like Objective-C, you can put nil to arguments which are class type without any restriction(might be). Argument otherButtonTitles is defined as non-optional which its type do not have (?)at its end. so you must pass a concrete value to it.
#IBAction func Alert(sender: UIButton) {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Alert!"
alertView.message = "Message"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
Try this
Use this code to display an alertview
let alertController = UIAlertController(title: "Hello Coders", message: "your alert message", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
Reference: Swift Show Alert using UIAlertController
in xcode 9
let alert = UIAlertController(title: "Alert", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
SWIFT 4 : Simply create a extension to UIViewController as follows:
extension UIViewController {
func showSuccessAlert(withTitle title: String, andMessage message:String) {
let alert = UIAlertController(title: title, message: message,
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK".localized, style:
UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
Now in your ViewController, directly call above function as if they are provided by UIViewController.
yourViewController.showSuccessAlert(withTitle:
"YourTitle", andMessage: "YourCustomTitle")
Or just do this
let alert = UIAlertController(title: "Alert", message: "Saved Successfully", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
try This.
Put Bellow Code In Button.
let alert = UIAlertController(title: "Your_Title_Text", message: "Your_MSG", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Your_Text", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated:true, completion: nil)
Here is a funny example in Swift:
private func presentRandomJoke() {
if let randomJoke: String = jokesController.randomJoke() {
let alertController: UIAlertController = UIAlertController(title:nil, message:randomJoke, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title:"Done", style:UIAlertActionStyle.Default, handler:nil))
presentViewController(alertController, animated:true, completion:nil)
}
}
Here is a pretty simple function of AlertView in Swift :
class func globalAlertYesNo(msg: String) {
let alertView = UNAlertView(title: "Title", message: msg)
alertView.messageAlignment = NSTextAlignment.Center
alertView.buttonAlignment = UNButtonAlignment.Horizontal
alertView.addButton("Yes", action: {
print("Yes action")
})
alertView.addButton("No", action: {
print("No action")
})
alertView.show()
}
You have to pass message as a String where you use this function.
The Old Way: UIAlertView
let alertView = UIAlertView(title: "Default Style", message: "A standard alert.", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
alertView.alertViewStyle = .Default
alertView.show()
// MARK: UIAlertViewDelegate
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
// ...
}
}
The New Way: UIAlertController
let alertController = UIAlertController(title: "Default Style", message: "A standard alert.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}

Resources