OGeek|极客世界-中国程序员成长平台

标题: ios - 使用 NSTimer 调用函数 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 17:02
标题: ios - 使用 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"
}



Best Answer-推荐答案


你可以试试这样的。方法是,如果定时器工作以相同的逻辑进行,否则(可能应用程序被杀死或进入后台),在方法 viewWillAppear 中显示 Controller 之前保存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()
        }
    }
}

关于ios - 使用 NSTimer 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493304/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4