Search code examples
xcodeswiftswift2xcode7

How to convert CLLocation to string in Xcode


I use SwiftLocation for get coordinates:

try! SwiftLocation.shared.currentLocation(Accuracy.House, timeout: 20, onSuccess: { (location) -> Void in
    print(location?.description)            
         }) { (error) -> Void in
    print("something went wrong")
         }

In location?.description I get it:

<+37.78583400,-122.40641700> +/- 5.00m (speed -1.00 mps / course -1.00) @ 2/22/16, 6:35:55 PM Indochina Time

And I need to take just coordinates. So I make loop for it:

    while name.characters.last != ">" { // delete all after ">"
        name = String(name.characters.dropLast())
    }
    name = String(name.characters.dropLast()) // delete ">"
    name = String(name.characters.dropFirst()) // delete "<"
    name = String(name.characters.dropFirst()) // delete "+"
    print(name) // get 37.78583400,-122.40641700
    tempMyLat = name
    while tempMyLat.characters.last != "," { // delete all after ","
        tempMyLat = String(tempMyLat.characters.dropLast())
    }
    tempMyLon = name
    while tempMyLon.characters.first != "," { // delete all before ","
        tempMyLon = String(tempMyLon.characters.dropFirst())
    }
    tempMyLon = String(tempMyLon.characters.dropFirst()) // delete ","

But this code work ONLY for string. When I get location?.description - I can't convert it for type - string, because "location" is a CLLocation type.

So, my question: How convert location?.description to String ? or how get only coordinates from the SwiftLocation

Thanks.


Solution

  • If you want to get locations from CLLocation you dont need to convert string from CLLocation object. you can get locations directly from CLLocation object. Here is an example :

    var locationObj = locationArray.lastObject as CLLocation
    var coord = locationObj.coordinate
    var longitude = coord.longitude //Latitude & Longitude as String
    var latitude = coord.latitude