hellosheikh
hellosheikh

Reputation: 3015

How can I pass a controller to a function

Hello I have a utility class in which I have declared AlertViewFunction like this

func displayAlertMessage(userMessage: String,//controller){
    let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
    let okAction =  UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
    myAlert.addAction(okAction);
    self.presentViewController(myAlert, animated: true, completion: nil)    
}

The problem is I can't use self here

self.presentViewController(myAlert, animated: true, completion: nil) 

I want to pass a controller to this function so I can use like this

controller.presentViewController(myAlert, animated: true, completion: nil) 

How Can I pass a controller from any ViewController. Lets say If I am in LoginViewController

Utility().displayAlertMessage(Message.INTERNETISNOTCONNECTED,//controller)

Upvotes: 2

Views: 86

Answers (2)

m.ding
m.ding

Reputation: 3182

Utility().displayAlertMessage(Message.INTERNETISNOTCONNECTED, controller: self)

and

func displayAlertMessage(userMessage: String, controller: UIViewController)
{
    controller?.presentViewController(myAlert, animated: true, completion: nil)
}

Upvotes: 2

Ahmed Onawale
Ahmed Onawale

Reputation: 4050

pass in the view controller as an argument to the function.

func displayAlertMessage(controller: UIViewController, title: String, message: String?) {
  let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
  let okAction =  UIAlertAction(title: "Ok", style: .Default, handler: nil)
  alert.addAction(okAction)
  controller.presentViewController(alert, animated: false, completion: nil)
}

Alternatively you can even return the alert to the caller of the function for further customization by saying:

func displayAlertMessage(title: String, message: String?) -> UIAlertController {
  let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
  let okAction =  UIAlertAction(title: "Ok", style: .Default, handler: nil)
  alert.addAction(okAction)
  return alert
}

class controller: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    let alert = displayAlertMessage("title", message: nil)
    presentViewController(alert, animated: true, completion: nil)
  }
}

Upvotes: 1

Related Questions