0

I'm receiving this JSON:

JSON: {
  "status_code" : 200,
  "status" : "ok",
  "data" : [
    {
      "zona" : "Narvarte",
      "hora" : "",
      "id_zona" : 1423,
      "proxdia" : "Lunes 20 de Febrero, 2017",
      "coor" : "(19.452187074041884, -99.1457748413086),(19.443769985032485, -99.14852142333984),(19.443446242121073, -99.13787841796875),(19.450244707639662, -99.13822174072266)",
      "dias" : "Lunes"
    }, ...]

Which I'm storing in this struct:

struct RutaItem {
var idZona: Int
var dias: String
var proxDia: String
var hora: String
var coor: String
var zona: String
}

then I created an array of [RutaItem] where I'm storing the structs

var rutaItemArray = [RutaItem]()

Once the data has been stored the structs inside rutaItemArray look like this:

[pixan.RutaItem(idZona: 1423, dias: "Lunes", proxDia: "Lunes 20 de Febrero, 2017", hora: "", coor: "(19.452187074041884, -99.1457748413086),(19.443769985032485, -99.14852142333984),(19.443446242121073, -99.13787841796875),(19.450244707639662, -99.13822174072266)", zona: "Narvarte")...]

What I need to do now is to use the String inside each index of rutaItemArray.coor to generate an MKPolygonObject, so first I would need to convert the long String into 4 CLLocationCoordinate2D objects and put those 4 coordinate objects inside an array for each item, then use the array indexes to generate the polygon.for the different areas.

Can somebody help me with this problem?

Octavio Rojas
  • 187
  • 13
  • Where does the `"coor"` array come from? It should be a json array of objects contains doubles, not a string like this – Alexander Feb 16 '17 at 22:32
  • it should but it doesn't and I'm not the programmer of the webservices, I'm just the iOS developer and I have to work with what I have unfortunately. If the Android developer could do it, it's certainly possible in iOS too. – Octavio Rojas Feb 16 '17 at 22:41

2 Answers2

2

Here's what I came up with. You can adapt it to fit your structure.

import Foundation

let input = "(19.452187074041884, -99.1457748413086),(19.443769985032485, -99.14852142333984),(19.443446242121073, -99.13787841796875),(19.450244707639662, -99.13822174072266)"

// Remove leading `(` and trailing `)`
let trimmedInput = String(input.characters.dropLast().dropFirst())

let coordStrings = trimmedInput.components(separatedBy: "),(")

let coords: [CLLocationCoordinate2D] = coordStrings.map{ coordsString in
    let coords = coordsString.components(separatedBy: ", ")
    precondition(coords.count == 2, "There should be exactly 2 coords.")
    guard let lat = Double(coords[0]),
          let long = Double(coords[1]) else {
        fatalError("One of the coords isn't a valid Double: \(coords)")
    }

    return CLLocationCoordinate2D(latitude: lat, longitude: long)
}

print(coords)
Alexander
  • 59,041
  • 12
  • 98
  • 151
2

You can use regular expression pattern matching. Explanations inline:

let coordString = "(19.452187074041884, -99.1457748413086), (19.443769985032485, -99.14852142333984),(19.443446242121073, -99.13787841796875),(19.450244707639662, -99.13822174072266)"

// Regular expression pattern for "( ... , ... )"
let pattern = "\\((.+?),(.+?)\\)"
let regex = try! NSRegularExpression(pattern: pattern)

// We need an NSString, compare http://stackoverflow.com/a/27880748/1187415
let nsString = coordString as NSString

// Enumerate all matches and create an array: 
let coords = regex.matches(in: coordString, range: NSRange(location: 0, length: nsString.length))
    .flatMap { match -> CLLocationCoordinate2D? in
        // This closure is called for each match.

        // Extract x and y coordinate from match, remove leading and trailing whitespace:
        let xString = nsString.substring(with: match.rangeAt(1)).trimmingCharacters(in: .whitespaces)
        let yString = nsString.substring(with: match.rangeAt(2)).trimmingCharacters(in: .whitespaces)

        // Convert to floating point numbers, skip invalid entries:
        guard let x = Double(xString), let y = Double(yString) else { return nil }

        // Return CLLocationCoordinate2D:
        return CLLocationCoordinate2D(latitude: x, longitude: y)
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • This solution works amazingly well! This is exactly what I was looking for but I'm not very good with regexes I lost almost a day trying to come up with a regex that did exactly this!! Thank you so much! – Octavio Rojas Feb 16 '17 at 23:34