swift - 计算总距离 swift iOS

标签 swift function methods distance tracking

因此,在我当前的项目 中,我正在使用一种方法来计算驾驶轻便摩托车与普通汽车相比节省的排放量。该函数包含两部分,方法(计算)和跟踪器函数。主要问题是跟踪器功能以某种方式似乎根本无法跟踪

我的主要问题是,如何让跟踪器功能在应用程序打开时始终跟踪?

这是追踪器功能

var startLocation:CLLocation!
var lastLocation: CLLocation!
var traveledDistance:Double = 0

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    if startLocation == nil {
        startLocation = locations.first
    } else {
        if let lastLocation = locations.last {
            let distance = startLocation.distanceFromLocation(lastLocation)
            let lastDistance = lastLocation.distanceFromLocation(lastLocation)
            traveledDistance += lastDistance
            print( "\(startLocation)")
            print( "\(lastLocation)")
            print("FULL DISTANCE: \(traveledDistance)")
            print("STRAIGHT DISTANCE: \(distance)")
            var travelDistance = setData("distance")
        }
    }
    lastLocation = locations.last
}

这是方法

func calculateEmission(numbers: Int...) -> Double{
    let recordedDistance = getData("distance")

    let dis = recordedDistance
    let emissionAve = 0.16

    let calculatedEmission : Double = Double(dis) * Double(emissionAve)

    print(calculatedEmission, "kg Co2")
    return calculatedEmission
}

最佳答案

确保您的 info.plist 中包含以下内容。然后系统会提示您允许访问定位服务。

<key>NSLocationAlwaysUsageDescription</key>
<string>Needs access to access GPS</string>
<key>NSLocationUsageDescription</key>
<string>Needs access to access GPS</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Needs access to access GPS</string>

你应该在 viewDidLoad 中有这样的东西。

override func viewDidLoad() {
    self.locationManager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }
    }

关于swift - 计算总距离 swift iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39005949/

相关文章:

ios - firebase 正在从数据库中检索已删除的数据

swift - 如何使用 PromiseKit 重构快速回调以实现 Promise

java - 将 String obj 添加到列表中的列表中

java - 返回字符串数组中的单词

java - 从 JSP 调用 Java 类方法

ios - 如何停止函数在 Swift 3.0 中运行

JavaScript 让独立的函数在不定义 new 的情况下工作

javascript - 如何在 Rails UJS 响应中使用 javascript 函数

regex - 如何编写验证字母数字和空格的正则表达式

xcode - 如何在 xcode 6.1.1 中打印出字典的值