【问题标题】:Convert String of CLLocationCoordinate2D(s) into array将 CLLocationCoordinate2D(s) 的字符串转换为数组
【发布时间】:2017-05-24 16:24:07
【问题描述】:

更新之前的问题以获得更好的解释。

var breadcrumbs: [CLLocationCoordinate2D] = []
var path: [CLLocationCoordinate2D] = []

每 10 秒调用一次,以将 CLLocationCoordinate2D 附加到数组。

func addBreadcrumb(){
    let speed = (locationmanager.location?.speed)!
    let speedRounded = speed.roundTo(places: 4)
    let crumbCoordinate = locationmanager.location?.coordinate

    breadcrumbs.append(crumbCoordinate!)
    tripSpeeds.append(speedRounded)
}

一旦用户完成旅行,他们点击一个按钮并调用以下函数。这会将数据输入到firebase。我将保存为字符串,否则会出错。

func submitTripPath(){
    let tripID: String? = tripUID
    let tripPath = String(describing: breadcrumbs) //This may be the problem
    let speeds = String(describing: tripSpeeds)

    var ref: FIRDatabaseReference!
    ref = FIRDatabase.database().reference()
    let tripRef = ref.child("TripPaths").child(tripID!)
    let tripDictionary = ["routePath" : tripPath, "routeSpeed" : speeds] as [String : Any]
    tripRef.updateChildValues(tripDictionary) { (err, ref) in
        if err != nil {
            print(err!)
            return
        }
    }
}

在另一个屏幕中,我成功提取了 Firebase 数据库参考中的坐标字符串。

let routePath = dict["routePath"] as! String //This may also be an issue
//output looks like this
"[__C.CLLocationCoordinate2D(latitude: 37.337728550000001, longitude: -122.02796406), __C.CLLocationCoordinate2D(latitude: 37.337716899999997, longitude: -122.02835139), __C.CLLocationCoordinate2D(latitude: 37.337694319999997, longitude: -122.0287719)]"

我希望能够将其用作 CLLocationCoordinate2D 中的数组来使用以下内容绘制折线。 我无法将此字符串转换为可用的 CLLocationCoordinate2D 数组。

    if (path.count > 1) {
        let sourceIndex = path.count - 1
        let destinationIndex = path.count - 2

        let c1 = path[sourceIndex]
        let c2 = path[destinationIndex]

        var a = [c1, c2]
        let polyline = MKPolyline(coordinates: &a, count: a.count)
        mapContainerView.add(polyline)
    }

如果您对保存原始数组、从 Firebase 中提取或转换字符串有任何建议,请告诉我。如果您需要其他代码供参考,请告诉我。

【问题讨论】:

  • 我不认为这是重复的,因为我在一个字符串中有许多 CLLocationCoordiante2D 的字符串,而不是每个字符串......我可以从中提取 lat/lng。我已经在使用单独的注释来做到这一点。如果您看到我如何将该答案应用于我的问题,您能进一步解释一下吗?
  • 该字符串最初是如何创建的?最好先想出一个更好的编码方法。
  • @rmaddy 在另一个屏幕中跟踪用户的路径,创建了一个 CLLocationCoordiante2D 数组并将其作为字符串保存在 firebase 中。如果我尝试将其保存为数组,则会出现错误:由于未捕获的异常“InvalidFirebaseData”而终止应用程序,原因:“(updateChildValues:withCompletionBlock :) 无法将 NSConcreteValue 类型的对象存储为 0。只能存储 NSNumber 类型的对象, NSString、NSDictionary 和 NSArray。'
  • 我知道它是一个字符串,但是有更好的方法可以将坐标数组转换为字符串,这样可以更容易地将字符串转换回坐标数组。您当前创建字符串的方法很难返回。我会重做您的问题,该问题更侧重于通过 Firebase 对一组坐标进行往返转换的最佳方式。包括您当前用于创建字符串的相关代码以及您对字符串进行解码的尝试。

标签: ios swift firebase firebase-realtime-database cllocation


【解决方案1】:

所以我认为你最大的问题是你使用的是字符串(描述:)。这将添加您看到的那些奇怪的类名。您最好想出自己的纬度/经度编码方法,然后对其进行反向编码以取回您的位置数据。所以像下面这样的方法会是一个更好的方法。

func submitTripPath(){
    let tripID: String? = tripUID
    let tripPath = encodeCoordinates(coords: breadcrumbs)
    let speeds = String(describing: tripSpeeds)

    var ref: FIRDatabaseReference!
    ref = FIRDatabase.database().reference()
    let tripRef = ref.child("TripPaths").child(tripID!)
    let tripDictionary = ["routePath" : tripPath, "routeSpeed" : speeds] as [String : Any]
    tripRef.updateChildValues(tripDictionary) { (err, ref) in
        if err != nil {
            print(err!)
            return
        }
    }
}

func encodeCoordinates(coords: [CLLocationCoordinate2D]) -> String {
    let flattenedCoords: [String] = coords.map { coord -> String in "\(coord.latitude):\(coord.longitude)" }
    let encodedString: String = flattenedCoords.joined(separator: ",")
    return encodedString
}

func decodeCoordinates(encodedString: String) -> [CLLocationCoordinate2D] {
    let flattenedCoords: [String] = encodedString.components(separatedBy: ",")
    let coords: [CLLocationCoordinate2D] = flattenedCoords.map { coord -> CLLocationCoordinate2D in
        let split = coord.components(separatedBy: ":")
        if split.count == 2 {
            let latitude: Double = Double(split[0]) ?? 0
            let longitude: Double = Double(split[1]) ?? 0
            return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        } else {
            return CLLocationCoordinate2D()
        }
    }
    return coords
}

我只是使用逗号和冒号进行编码,但您可以轻松使用其他内容。

【讨论】:

  • 实现这一点要记住的一点是,我在示例代码中几乎没有进行错误检查。特别是在解码中,您可能希望确保解码始终返回有效的 CLLocationCoordiante2D 而不仅仅是一个空的 init。
  • 这看起来很有趣。它工作得很好,将数据输入数据库,但使用 decodeCoordinates 不起作用,因为它显示错误:无法将“String”类型的值转换为预期的参数类型“NSCoder”,来自,让 routePath = dict[” routePath"] 一样! Firebase 参考中的字符串。将其作为 NSCoder 拉出来也不行。
  • 你应该能够做到以下let routePath: String = dict["routePath"] as! String path = decodeCoordinates(encodedString: routePath)
  • print(routePath) 从数据库中取出后会是什么样子?理论上它应该看起来像“180:180,90:90”。
  • 您的答案有效!感谢您在这方面帮助我并坚持我!我已经接受了这个答案。我相信这个答案将来会帮助很多人。
猜你喜欢
  • 1970-01-01
  • 2015-04-09
  • 1970-01-01
  • 2015-08-28
  • 2019-05-23
  • 2017-11-27
  • 2011-06-18
相关资源
最近更新 更多