私はバックグラウンドでタイマーを実行する必要はないと思っています。あなたが必要とするのは、一時停止中に経過した時間を知ることです。これは、空のサウンドファイルを再生しようとするよりも、リソースをはるかに使いやすくしています。
applicationWillResignActive
とapplicationDidBecomeActive
を使用して、どれだけの時間が経過したかを判断します。まず、あなたのタイマーのfireDateを保存し、applicationWillResignActive
func applicationWillResignActive(application: UIApplication) {
guard let t = self.timer else { return }
nextFireDate = t.fireDate
t.invalidate()
}
次でそれを無効にする、あなたはapplicationWillResignActive
コールに保存されているどのくらいの時間fireDateに今の時間を比較することにより、applicationDidBecomeActive
にタイマー放置されて決定します。
あなたは1を繰り返す必要がある場合は
func applicationDidBecomeActive(application: UIApplication) {
guard let n = nextFireDate else { return }
let howMuchLonger = n.timeIntervalSinceDate(NSDate())
if howMuchLonger < 0 {
print("Should have already fired \(howMuchLonger) seconds ago")
target!.performSelector(selector!)
} else {
print("should fire in \(howMuchLonger) seconds")
NSTimer.scheduledTimerWithTimeInterval(howMuchLonger, target: target!, selector: selector!, userInfo: nil, repeats: false)
}
}
、ちょうどタイマーが発射されている必要がありますどのように多くの時間を把握するために数学を行うながら、バックグラウンドで
let howManyTimes = abs(howMuchLonger)/repeatInterval
時間ttp://stackoverflow.com/questions/8415870/scheduled-nstimer-when-app-is-in-background – rakeshbs
なぜタイマーをバックグラウンドで実行する必要がありますか? – matt