gpt4 book ai didi

ios - 如何在iOS中获取用户所在位置的经纬度

转载 作者:搜寻专家 更新时间:2023-10-31 08:23:47 25 4
gpt4 key购买 nike

我是 Swift 的新手,我需要获取用户的当前位置。我的意思是我需要获取纬度和经度。我试过这个:

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

在这里我可以获得坐标,但它看起来像:

<+55.75590390,+37.61744720> +/- 100.00m (speed -1.00 mps / course -1.00) @ 2/14/15, 10:48:14 AM Moscow Standard Time

如何只检索纬度和经度?

最佳答案

为 Swift 3.x 和 Swift 4.x 更新了代码

据我所知,您在代码中使用了 print(placemark.location)

因此,如果您只想获得纬度,请使用此代码

print(placemark.location.coordinate.latitude)

如果你只想获取经度,请使用此代码

print(placemark.location.coordinate.longitude)

希望对您有所帮助!

关于ios - 如何在iOS中获取用户所在位置的经纬度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28513627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com