我有一个本地警报设置,可在预先指定的时间(30秒)启动。我想要做的是在20秒时发出警报。这是我的相关appDelegate代码:
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()
}
现在我已经看到了这个答案How can I use NSTimer in Swift?
但我不希望finalAlert功能立即启动。我想让它在初始警报后开启10秒。如何让NSTimer等待10秒钟来发出警报,还是有更好的方法等待?
答案 0 :(得分:1)
等待10秒
我不清楚你认为NSTimer的行为有什么问题,但无论如何最简单的方式表达“从现在起10秒后做这个”的概念就是使用GCD的dispatch_after
。最简单的方法 就像我在这里封装它一样:dispatch_after - GCD in swift?
答案 1 :(得分:1)
NSTimer字面意思是不立即开火。你启动计时器的时间间隔是你想要它发射的时间,我猜你的情况是10秒。
//first parameter is a time interval in seconds target is self and selector is
//finalAlert, which means after 10 seconds it will call self.finalAlert
//userInfo is nil, because you aren't passing any additional info
//and repeats is false, because you only want the timer to run once.
let timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: "finalAlert", userInfo: nil, repeats: false)