I'm using the CoreMotion framework, and it works, but now I'd like to add a timer that loads a method after 5 seconds.
If 5 seconds have not passed load another method.
the problem is that in the debug area it doesn't print "STOPMAP" or "STARTMAP" so I think the timer doesn't work, where am I wrong?
import UIKit
import CoreMotion
private let motionActivityManager = CMMotionActivityManager()
class ViewController: UIViewController {
@IBOutlet weak var lblActivity: UILabel!
var second = 0
override func viewDidLoad() {
super.viewDidLoad()
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(calculateSeconds), userInfo: nil, repeats: true)
motionActivityManager.startActivityUpdates(to: OperationQueue.main) { (activity: CMMotionActivity?) in
guard let activity = activity else { return }
DispatchQueue.main.async {
if activity.stationary {
self.lblActivity.text = "Stationary"
print("Stationary")
calculate()
} else if activity.walking {
self.lblActivity.text = "Walking"
print("Walking")
} else if activity.running {
self.lblActivity.text = "Running"
print("Running")
} else if activity.automotive {
self.lblActivity.text = "Automotive"
print("Automotive")
}
}
}
}
@objc func calculateSeconds() {
second += 1
}
func calculate() {
if second > 5 {
stopMap()
} else {
startMap()
}
second = 0
timer.invalidate()
timer = nil
}
func stopMap() {
print("STOPMAP")
}
func startMap() {
print("STARTMAP")
}
}
Here is the solution, this will resolve the issue of timer. Test it on real device.