想要延迟函数调用

Want to delay function call

我将本地警报设置为在预先指定的时间(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 秒来触发警报,或者有更好的等待方法吗?

wait 10 seconds

我不清楚您认为 NSTimer 的行为有什么问题,但无论如何,表达概念 "do this, 10 seconds from now" 的最简单方法是使用 GCD 的 dispatch_after。最简单的方法 就是我在此处封装的方法:dispatch_after - GCD in swift?

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)