Ios 要延迟函数调用吗
我有一个本地警报设置为在预先指定的时间(30秒)触发。我要做的是在20秒时发出警报。这是我的相关appDelegate代码:Ios 要延迟函数调用吗,ios,swift,nstimer,Ios,Swift,Nstimer,我有一个本地警报设置为在预先指定的时间(30秒)触发。我要做的是在20秒时发出警报。这是我的相关appDelegate代码: func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { // Pass the "firing" event onto the notification manager timerNotific
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()
}
现在我看到了这个答案
但我不希望finalAlert函数立即启动。我希望它在初始警报10秒后发射。我如何让NSTimer等待10秒来触发警报,还是有更好的等待方式
等10秒钟
我不清楚您认为NSTimer的行为有什么问题,但无论如何,表达“从现在开始10秒后执行此操作”这一概念的最简单方法是使用GCD的
dispatch\u after
。最简单的方法就是我在这里封装它: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)
我是一个初学者,所以如果我问得不恰当,我很抱歉。但正如目前的代码所示,两个警报都会紧接着发出,而不是像我希望的那样延迟。但我不知道关于after或GCD的调度。还有-performSelector:afterDelay:withObject,非常易于使用。这在swift中已被弃用。可能与