swift - 提供获取当前速度的简单方法(实现速度计)

标签 swift core-location

能否请您举例说明如何计算当前“速度”,我正在开发我的第一个简单应用程序 ala speedometer?

我想出使用 didUpdateToLocation

我还发现我需要使用公式 speed = distance/duration

是吗?如何计算持续时间?

最佳答案

您需要完成的基本步骤如下所示:

  1. 创建一个 CLLocationmanager 实例
  2. 指派一名代表 适当的回调方法
  3. 检查是否在回调中的 CLLocation 上设置了“速度”,如果是 - 这是您的速度
  4. (可选)如果“速度”不是 设置,尝试从上次更新之间的距离计算它 和当前,除以时间戳的差值

    import CoreLocation
    
    class locationDelegate: NSObject, CLLocationManagerDelegate {
        var last:CLLocation?
        override init() {
          super.init()
        }
        func processLocation(_ current:CLLocation) {
            guard last != nil else {
                last = current
                return
            }
            var speed = current.speed
            if (speed > 0) {
                print(speed) // or whatever
            } else {
                speed = last!.distance(from: current) / (current.timestamp.timeIntervalSince(last!.timestamp))
                print(speed)
            }
            last = current
        }
        func locationManager(_ manager: CLLocationManager,
                     didUpdateLocations locations: [CLLocation]) {
            for location in locations {
                processLocation(location)
            }
        }
    }
    
    var del = locationDelegate()
    var lm = CLLocationManager();
    lm.delegate = del
    lm.startUpdatingLocation()
    

关于swift - 提供获取当前速度的简单方法(实现速度计),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38512443/

相关文章:

ios - 在 Watchkit Target 中使用 Swift 创建数据类

objective-c - 多个 View 使用的 CoreLocation 单例委托(delegate)方法

ios - CLLocationManager 在蜂窝网络 (3G) 中无法获取位置精度

iphone - 像foursquare或gowalla这样的应用程序是如何实现他们的签到功能的?

ios - 手机锁定后位置访问权限警报消失

iOS,CoreLocation - 在应用加载时获取用户位置

ios - 真机上Glance访问IBOutlet时出现WatchKit "unexpectedly found nil while unwrapping an Optional value"

arrays - 根据用户在 Swift 中的选择从数组加载自定义单元格值

ios - @IBDesignable UIView 具有固定高度

swift - 失败部分未返回 Alamofire 状态代码