我正在使用 CoreMotion 框架,它可以工作,但现在我想添加一个计时器,在 5 秒后加载一个方法。
如果 5 秒尚未过去,则加载另一个方法。
问题是在调试区域它没有打印“STOPMAP”或“STARTMAP”,所以我认为计时器不起作用,我错在哪里?
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")
}
}
这是解决方案,这将解决计时器的问题。 在真实设备上测试一下。
import CoreMotion
import UIKit
private let motionActivityManager = CMMotionActivityManager()
class ViewController: UIViewController {
var second = 0
var timer: Timer?
public func addTimer() {
motionActivityManager.startActivityUpdates(to: OperationQueue.main) { (activity: CMMotionActivity?) in
guard let activity = activity else { return }
DispatchQueue.main.async {
print(activity)
if activity.stationary {
print("Stationary")
// Add a 5-second timer when the activity becomes "Stationary"
self.startTimer()
} else if activity.walking {
print("Walking")
// Stop the timer when the activity changes
self.stopTimer()
} else if activity.running {
print("Running")
// Stop the timer when the activity changes
self.stopTimer()
} else if activity.automotive {
print("Automotive")
// Stop the timer when the activity changes
self.stopTimer()
}
}
}
}
@objc func updateTimer() {
second += 1
if second >= 5 {
// Execute your action when the timer reaches 5 seconds
self.timerFired()
}
}
func startTimer() {
// Create a 1-second repeating timer
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
func stopTimer() {
// Stop and invalidate the timer
timer?.invalidate()
timer = nil
second = 0
}
func timerFired() {
// Implement the action you want to take when the timer fires (after 5 seconds)
print("Timer fired after 5 seconds!")
// You can add your logic here, such as stopping the activity updates.
// For example, self.motionActivityManager.stopActivityUpdates()
}
}