I would like to pass parameters to the following function through userInfo
, because that function has to execute after delay.
func showAlert(alertTitle: String, withMessage alertMessage: String, fromController controller: UIViewController) {
//do stuff...
}
Have already done that part with delay, but I do not know how to send multiple parameters to the body of showAlert.
func fireTimer() {
timer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("showAlert:"), userInfo: nil, repeats: false)
}
Your assistance would be very much appreciated.
I'm still getting errors, don't know why.
unrecognized selector sent to instance
This is how my code looks like. What's wrong?
class AlertController: UIAlertController {
var timer = NSTimer()
func showAlert(alertTitle: String, withMessage alertMessage: String, fromController controller: UIViewController)
{
var alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .Alert)
controller.presentViewController(alert, animated: true, completion: nil)
}
func showAlert2(dict: [String: AnyObject])
{
showAlert(dict["title"] as! String,
withMessage: dict["message"] as! String,
fromController: dict["controller"] as! UIViewController)
}
func fireTimer(title: String, message: String, viewController: UIViewController)
{
timer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("showAlert2:"), userInfo: ["title":title, "message": message, "controller": viewController], repeats: false)
}
You cannot pass more than one parameter using NSTimer, however, you can make that parameter into an array or ditionary or similar.
Then create a new function that takes that array/dictionary and then calls your function with every parameter inside the array/dictionary
func fireTimer() {
timer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("showAlert2:"), userInfo: ["title":"a title", "message": "a message", "controller": controller], repeats: false)
}
func showAlert2(timer: NSTimer) {
let dict = timer.userInfo as NSDictionary
showAlert(dict["title"] as String, wwithMessage: dict["message"] as String, fromController: dict["controller"] as UIViewController)
}
func showAlert(alertTitle: String, withMessage alertMessage: String, fromController controller: UIViewController) {
// do stuff...
}