使用 NSTimer 调用函数

Call a function using NSTimer

因此,如下所示,函数 loadView 3 应该在用户点击按钮后 运行 300 秒(5 分钟)。但是当我构建 运行 时,它没有。我也做了一些实验,我把定时器改成 5 秒,成功了。那么在应用程序从 iOS 系统暂停后,NSTimer 不再 运行 了吗?那么这是什么问题,我该如何解决?

@IBAction func buttonTapped(sender: AnyObject) {
    NSTimer.scheduledTimerWithTimeInterval(300, target: self, selector: #selector(ViewController.loadView3), userInfo: nil, repeats: false)    
    createLocalNotification()
}

func createLocalNotification() {
    let localnotification = UILocalNotification()
    localnotification.fireDate = NSDate(timeIntervalSinceNow: 300)
    localnotification.applicationIconBadgeNumber = 1
    localnotification.soundName = UILocalNotificationDefaultSoundName
    localnotification.alertBody = "Hello!"
    UIApplication.sharedApplication().scheduleLocalNotification(localnotification)
}

func loadView3() {
    label.text = "e89saa"
}

你可以尝试这样的事情。方法是,如果计时器以相同的逻辑继续工作,否则(可能应用程序被杀死或进入后台),在方法 viewWillAppear 中显示控制器之前保存 firedDate 并更新 UI。

@IBAction func buttonTapped(sender: AnyObject) {
    NSTimer.scheduledTimerWithTimeInterval(300, target: self, selector: #selector(ViewController.loadView3), userInfo: nil, repeats: false)    
    createLocalNotification()
}

func createLocalNotification() {
    let localnotification = UILocalNotification()
    localnotification.fireDate = NSDate(timeIntervalSinceNow: 300)
    localnotification.applicationIconBadgeNumber = 1
    localnotification.soundName = UILocalNotificationDefaultSoundName
    localnotification.alertBody = "Hello!"
    UIApplication.sharedApplication().scheduleLocalNotification(localnotification)

    // save in UserDefaults fireDate
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(localnotification.fireDate, forKey: "firedDate")
    defaults.synchronize()
}

func loadView3() {
    // reset in UserDefaults fireDate
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.removeObjectForKey("firedDate")
    defaults.synchronize()

    label.text = "e89saa"
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated) // No need for semicolon

    // retrieve fireDate from UserDefaults
    let defaults = NSUserDefaults.standardUserDefaults()
    let fireDate = defaults.objectForKey("firedData")

    // check if we should update UI
    if let _ = fireDate as? NSDate! {
        if currentDate.compare(firedDate) == NSComparisonResult.OrderedDescending {
            loadView3()
        }
    }
}