I am a new in Swift and I need to get the current location of a user. I mean that I need to get latitude and longitude. I have tried this:
class ViewController: UIViewController, CLLocationManagerDelegate{
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error) -> Void in
if (error != nil) {
println("ERROR:" + error.localizedDescription)
return
}
if placemarks.count > 0 {
let pm = placemarks[0] as CLPlacemark
self.displayLocationInfo(pm)
} else {
println("Error with data")
}
})
}
func displayLocationInfo(placemark: CLPlacemark) {
// self.locationManager.stopUpdatingLocation()
println(placemark.locality)
println(placemark.postalCode)
println(placemark.administrativeArea)
println(placemark.country)
println(placemark.location)
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError) {
println("Error:" + error.localizedDescription)
}
}
And here I can get coordinates, but it will looks like:
<+55.75590390,+37.61744720> +/- 100.00m (speed -1.00 mps / course -1.00) @ 2/14/15, 10:48:14 AM Moscow Standard Time
How can I retrieve only latitude and longitude?
Code updated for Swift 3.x and Swift 4.x
As I can see you have used print(placemark.location)
in your code.
So if you want to get only latitude use this code
print(placemark.location.coordinate.latitude)
and if you want to get only longitude use this code
print(placemark.location.coordinate.longitude)
Hope this helps !