2016-07-21 11 views
2

以下に示すコードのように、loadView 3関数は、ユーザーがボタンをタップしてから300秒(5分)実行されるはずです。しかし、私が構築して実行すると、それはしません。私もいくつかの実験を行い、タイマーを5秒に変更しました。アプリがiOSシステムから中断された後、NSTimerはもう動かないのですか?それで問題は何ですか、どうすれば修正できますか?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" 
} 
+1

バックグラウンドタスクリクエスト(5分未満の制限)がある場合やアプリがバックグラウンドの場所や音楽サービスを持っている場合を除き、アプリがバックグラウンドになるとNSTimersは実行されません。あなたのアプリが5分間フォアグラウンドに留まる場合、タイマーは正常に機能しますか? – Putz1103

+0

アプリがフォアグラウンドのままであれば、タイマーは正常に機能します。他の方法はありますか? 5分後にビューを変更したいだけで、NSTimerで行う必要はありません。しかし、NSTimerは私が今知っている唯一の方法です。 – Joe

+0

私のアプリがバックグラウンドのときにdispatch_after()が機能しますか? – Joe

答えて

0

あなたはこのようなことを試すことができます。このアプローチは、タイマーの作業が同じロジックで処理される場合、そうでなければ(おそらくアプリが強制終了またはバックグラウンドに移行する)、firedDateを保存してUIを更新してから、viewWillAppearメソッドでコントローラを表示します。

@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() 
     } 
    } 
} 
関連する問題