Swift 画面遷移しても継続してカウントダウンして欲しい。
UserDefaultを使ってみるも良く分からず。。。
import UIKit
class NextViewController: UIViewController {
var timer : Timer?
var date1 : Date?
var date2 : Date?
var count = 15.0
@IBOutlet weak var countDownLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func startButton(_ sender: UIButton) {
date1 = Date()
if timer?.isValid != true {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fifteenCount(_:)), userInfo: nil, repeats: true)
}
}
@objc func fifteenCount (_ timer : Timer) {
date2 = Date()
let dateDifference = date2!.timeIntervalSince(date1!)
count = 15 - dateDifference
countDownLabel.text = String(Int(count))
if count <= 0 {
timer.invalidate()
}
}
}