我對swift比較陌生,我試圖在我的應用中添加一個功能,該功能跟蹤在受限時間內行進的距離。使用核心位置時的不精確的距離旅行值
但是,當我運行該應用程序時,即使手機接收到的經緯度是準確的,我仍然遇到多個問題: 1.該應用程序只記錄位置變化幾秒鐘 2.應用程序記錄即使設備靜止不動也會發生劇烈運動。
任何和所有的幫助表示讚賞。這裏是我的代碼:
import UIKit
import CoreLocation
import FirebaseAuth
import FirebaseDatabase
class MWTCountdownViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var metersLabel: UILabel!
@IBOutlet weak var ConfirmTrialButton: UIButton!
var zeroTime = TimeInterval()
var timer : Timer = Timer()
var ref: DatabaseReference?
let locationManager = CLLocationManager()
var startLocation: CLLocation!
var lastLocation: CLLocation!
var distanceTraveled: Double = 0.0
override func viewDidLoad() {
super.viewDidLoad()
ConfirmTrialButton.isHidden = true
ConfirmTrialButton.isEnabled = false
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
distanceTraveled = 0.0
startLocation = nil
lastLocation = nil
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
locationManager.distanceFilter = 10
} else {
print("Need to Enable Location")
}
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(MWTCountdownViewController.updateTime), userInfo: nil, repeats: true)
zeroTime = Date.timeIntervalSinceReferenceDate
ref = Database.database().reference()
}
func updateTime() {
let currentTime = Date.timeIntervalSinceReferenceDate
var timePassed: TimeInterval = currentTime - zeroTime
let minutes = UInt8(timePassed/60.0)
timePassed -= (TimeInterval(minutes) * 60)
let seconds = UInt8(timePassed)
timePassed -= TimeInterval(seconds)
let millisecsX10 = UInt8(timePassed * 100)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strMSX10 = String(format: "%02d", millisecsX10)
timerLabel.text = "\(strMinutes):\(strSeconds):\(strMSX10)"
if timerLabel.text == "06:00:00" {
timer.invalidate()
locationManager.stopUpdatingLocation()
ConfirmTrialButton.isHidden = false
ConfirmTrialButton.isEnabled = true
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if startLocation == nil {
startLocation = locations.first as CLLocation!
} else if let location = locations.last {
let lastDistance = lastLocation.distance(from: location)
distanceTraveled += lastDistance
let trimmedDistance = String(format: "%.2f", distanceTraveled)
metersLabel.text = "\(trimmedDistance) m"
}
lastLocation = locations.last as CLLocation!
}
我將不勝感激任何示例代碼添加爲了解決這個問題。謝謝。 – solthums