How to Create Uialertcontroller in Global Swift

How to create uialertcontroller in global swift

self.window would mean that there's a window object in this class, and it's not the case.

You would need to use your let window : UIWindow? with window?.presentViewController(alert, animated: true, completion: nil), but this won't help, since this window does not actually represent any existing window, and it's not a view controller anyway.

So I suggest you pass the actual view controller you'll be using to the method:

static func showAlertMessage(vc: UIViewController, titleStr:String, messageStr:String) -> Void {
let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.Alert);
vc.presentViewController(alert, animated: true, completion: nil)
}

and you call it from a class where a UIViewController object is available.

UIAlertController creation in global method

In order to have a global function able to show the alert, you might use an extension like this one:

extension UIViewController {
func showAlert(_ completion:@escaping ()->()) {
let alert = UIAlertController(title: "Delete", message: "Really delete?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { (action) in
completion()
}))
alert.addAction(UIAlertAction(title: "No", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}

and then whenever you need to show the alert you just call showAlert passing the completion you would like to be executed (in case of Yes); eg: from your ViewController you might use this:

self.showAlert {
self.deleteHistoryRecord(forRecordID: self.shistIDs[indexPath.row])
}

How to make a global function for UIAlertController(ActionSheet) to access in many classes of project

I have found solution of my problem by using this Swift - How to present ViewController when tapping button in a custom AlertController

Their are following modification that I have to do to achieve my goal. Here is the code:

In Controller Class:

 Alert.showActionSheet(self, message: "Save incoming media for this chat",strtittle: "",actionTittle: ["Default(Off)","Always","Never","Cancel"],
actionStyle: [.default,.default,.default,.cancel] ,
withHandler: [defaultHandler, alwaysHandler, neverHandler, cancelHandler])

func defaultHandler(action: UIAlertAction) {
//Add code of present
print("DefaultHandler")
}

func alwaysHandler(action: UIAlertAction) {
//Add code of present
print("alwaysHandler")

}

func neverHandler(action: UIAlertAction) {
//Add code of present
print("neverHandler")
}

func cancelHandler(action: UIAlertAction) {
//Add code of present
print("cancelHandler")
}

In NSObject Class:

open class func showActionSheet(_ delegate: UIViewController, message: String, strtittle: String, actionTittle: [String], actionStyle: [UIAlertActionStyle], withHandler handler: [((UIAlertAction) -> Void)]?)
{
var actionSheetController: UIAlertController = UIAlertController()

if message != "" || strtittle != ""
{
actionSheetController = UIAlertController(title: strtittle, message: message, preferredStyle: UIAlertControllerStyle.actionSheet)
}

for i in 0..<actionTittle.count
{
actionSheetController.addAction(UIAlertAction(title: actionTittle[i],
style: actionStyle[i],
handler: handler?[i]))
}

delegate.present(actionSheetController, animated: true, completion: nil)

}

Using this I can gave number of actions, their tittle and styles to action sheet. And also I can simply call this method in each class. :)

How would I create a UIAlertView in Swift?

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)

How to use UIAlertController() as global variable on iOS7 compatible devices?

For anyone else that might stumble upon this,

class Alerts {

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var iOS8Up: Bool = true

lazy var alertControllerLoad = Alerts.set()
let alertViewLoad = UIAlertView()

class func set() -> UIAlertController {

//get the device model to know what image to post for refresh
var device : UIDevice = UIDevice.currentDevice();
var systemVersion = device.systemVersion;
let numberFormatter = NSNumberFormatter()
let systemVersionNumber = numberFormatter.numberFromString(systemVersion)
let systemVersionFloatValue = systemVersionNumber!.floatValue

if(systemVersionFloatValue < 8.0) {
return UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.Alert)
}
else{
//returns with actionSheet as preferredStyle
//will crash on anything less than iOS8
return UIAlertController()
}

}

}

this allows you to make a AlertController a global variable even if you're running iOS7. I spent far too long on this issue.

Swift UIAlertController showing custom message

Why not simply an extension?

extension UIViewController {

func presentAlert(withTitle title: String, message : String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { action in
print("You've pressed OK Button")
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
}

and call it with

presentAlert(withTitle: "Error", message: "error")

in any UIViewController class

How to add alert message to a global class

You can create a UIViewController extension and implement this method there. This will allow you to call it from any UIViewController subclass.

extension UIViewController {

func displayAlertMessage(title: String, message: String)
{
let alertMessage = UIAlertController(title: title, message: message, preferredStyle:UIAlertControllerStyle.alert);

let okAction = UIAlertAction(title:"OK", style: .default, handler:nil);

alertMessage.addAction(okAction);

self.present(alertMessage, animated: true, completion: nil);
}
}

You could also add a handler and completion parameters to the displayAlertMessage function, which would allow you to customize the both the action handler and what happens when the alert finishes being presented, from the calling point.

How to change global value (add function) in the handler of UIAlertAction of UIAlertController?

how do you get a reference to the AppDelegate? the following code should work:

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var globalValue = false

}

class ViewController: UIViewController {

var appDelegate: AppDelegate {
return UIApplication.sharedApplication().delegate as! AppDelegate
}

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

let alert = UIAlertController(title: nil, message: "set global value to true", preferredStyle: .Alert)
let action = UIAlertAction(title: "ok", style: .Default) { (action) in
self.appDelegate.globalValue = true
print("after: \(self.appDelegate.globalValue)")
}
alert.addAction(action)

print("before: \(self.appDelegate.globalValue)")
presentViewController(alert, animated: true, completion: nil)
}

}

How to present UIAlertController when not in a view controller?

I posted a similar question a couple months ago and think I've finally solved the problem. Follow the link at the bottom of my post if you just want to see the code.

The solution is to use an additional UIWindow.

When you want to display your UIAlertController:

  1. Make your window the key and visible window (window.makeKeyAndVisible())
  2. Just use a plain UIViewController instance as the rootViewController of the new window. (window.rootViewController = UIViewController())
  3. Present your UIAlertController on your window's rootViewController

A couple things to note:

  • Your UIWindow must be strongly referenced. If it's not strongly referenced it will never appear (because it is released). I recommend using a property, but I've also had success with an associated object.
  • To ensure that the window appears above everything else (including system UIAlertControllers), I set the windowLevel. (window.windowLevel = UIWindowLevelAlert + 1)

Lastly, I have a completed implementation if you just want to look at that.

https://github.com/dbettermann/DBAlertController



Related Topics



Leave a reply



Submit