【问题标题】:Want to delay function call想要延迟函数调用
【发布时间】:2015-02-18 03:50:04
【问题描述】:

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

【问题讨论】:

标签: ios swift nstimer


【解决方案1】:

等待 10 秒

我不清楚您认为 NSTimer 的行为有什么问题,但无论如何,表达“从现在开始 10 秒后执行此操作”这一概念的最简单方法是使用 GCD 的dispatch_after 最简单的方法就是我在这里封装它:dispatch_after - GCD in swift?

【讨论】:

  • 我是一个初学者,如果我没有正确地问这个问题,我很抱歉。但正如目前的代码一样,两个警报会立即触发,而不是我想要的延迟。但我不知道调度后或 GCD。
  • 还有-performSelector:afterDelay:withObject,非常好用。
  • 这在 swift 中已被弃用。
【解决方案2】:

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)

【讨论】:

    猜你喜欢
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    相关资源
    最近更新 更多