2017-05-24 1 views
0

더 나은 설명을 위해 이전 질문을 업데이트하십시오.CLLocationCoordinate2D의 문자열을 배열로 변환하십시오.

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

CLLocationCoordinate2D를 배열에 추가하기 위해 10 초마다 호출됩니다.

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에 데이터를 가져옵니다. 그렇지 않으면 오류가 발생하여 Strings로 저장 중입니다.

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) 
    } 

당신이 원래의 배열을 저장 베팅 중포 기지에서 잡아 당겨, ​​또는 알려 주시기 바랍니다 문자열을 변환하는 방법에 대한 제안이있는 경우. 참조 할 다른 코드가 필요하면 알려주십시오.

+0

[신속하게 CLLocationCoordinate2D로 문자열 변환] 가능한 복제본 (https://stackoverflow.com/questions/28417512/convert-string-to-collocationcoordinate2d-in-swift) – shallowThought

+0

나는 이것이 다음과 같이 중복되지 않는다고 생각합니다. 하나의 문자열에 많은 CLLocationCoordiante2D 문자열이 있습니다. 각각의 문자열은 아닙니다 ... 위도/Lng를 가져올 수 있습니다. 나는 이미 개별적인 주석으로이를 수행하고있다. 내 질문에 그 대답을 어떻게 적용 할 수 있는지를 알면 더 설명 할 수 있습니까? –

+0

처음에 문자열이 어떻게 생성 되었습니까? 먼저 더 나은 인코딩 방법을 제안하는 것이 좋습니다. – rmaddy

답변

3

그래서 가장 큰 문제는 String을 사용하고 있다는 것입니다 (설명 :). 이것은보고있는 이상한 클래스 이름을 추가 할 것입니다. 위도/경도에 대한 자체 인코딩 방법을 고안 한 다음 역 인코딩하여 위치 데이터를 가져 오는 것이 좋습니다. 그래서 다음과 같은 것이 bette 접근 방식 일 것입니다.

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 
} 

나는 단지 인코딩을 위해 쉼표와 콜론을 사용했지만 다른 것을 쉽게 사용할 수 있습니다.

+0

이것을 구현하는 것을 기억해야 할 한 가지는 예제 코드에서 오류를 거의 확인하지 않았다는 것입니다. 특히 디코딩에서는 디코드가 항상 빈 CALLocationCoordiante2D 및 빈 init 만 반환하도록 할 수 있습니다. –

+0

흥미로운 것 같습니다. 데이터를 데이터베이스로 가져 오는 데는 효과가 있지만 decodeCoordinates를 사용하면 다음과 같은 오류가 표시되어 작동하지 않습니다. 'String'유형의 값을 예상되는 인수 유형 'NSCoder'로 변환 할 수 없습니다. routePath = dict [ " routePath "]! firebase 참조의 문자열. NSCoder로 당겨도 작동하지 않습니다. –

+1

다음과 같이하면됩니다 :'let routePath : String = dict [ "routePath"]! String path = decodeCoordinates (encodedString : routePath)' –

관련 문제