I have a local alert set to fire off at a predesignated time (30 seconds). What I want to do is fire off an alert at 20 seconds. This is my relevant appDelegate code:
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
// Pass the "firing" event onto the notification manager
timerNotificationManager.timerFired()
if application.applicationState == .Active {
//let alert = UIAlertController(title: "NotifyTimely", message: "Your time is up", preferredStyle: .Alert)
// Handler for each of the actions
let actionAndDismiss = {
(action: String?) -> ((UIAlertAction!) -> ()) in
return {
_ in
self.timerNotificationManager.handleActionWithIdentifier(action)
self.window?.rootViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}
/*
alert.addAction(UIAlertAction(title: "Dismiss", style: .Cancel, handler: actionAndDismiss(nil)))
alert.addAction(UIAlertAction(title: "Restart", style: .Default, handler: actionAndDismiss(restartTimerActionString)))
alert.addAction(UIAlertAction(title: "Snooze", style: .Destructive, handler: actionAndDismiss(snoozeTimerActionString)))
window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
*/
var ourAlert = UIAlertView(title: "Time Alert", message: "You have been active for 20 seconds!", delegate: nil, cancelButtonTitle: "Dismiss")
ourAlert.show()
self.finalAlert()
}
}
func finalAlert() {
let alert = UIAlertView()
alert.title = "Final Timer Alert"
alert.message = "You have been active for 20 seconds. Your ride is now being charged."
alert.addButtonWithTitle("OK")
alert.show()
}
Now I have seen this answer How can I use NSTimer in Swift?
But I don't want the finalAlert function to kick off immediately. I want it to fire off 10s after the initial alert. How do I get NSTimer to wait 10 seconds to fire the alert or is there a better way to wait?
wait 10 seconds
It's unclear to me what you think is wrong with the behavior of NSTimer, but in any case the simplest way to express the notion "do this, 10 seconds from now" is to use GCD's dispatch_after
. And the easiest way to do that is as I encapsulate it here: dispatch_after - GCD in swift?