gpt4 book ai didi

ios - 如何通过单击 uibutton 获取标签中的用户纬度和经度

转载 作者:行者123 更新时间:2023-11-29 06:00:21 24 4
gpt4 key购买 nike

我正在尝试使用反向 CLgeocoding 来获取用户当前位置的纬度和经度。但是,我认为方法没有被调用。至少我没有在控制台中得到任何结果。如果有人帮助我做到这一点,那就太好了。提前致谢。

import UIKit
import CoreLocation

class ViewController: UIViewController,CLLocationManagerDelegate {

@IBOutlet weak var lbl2: UILabel!
@IBOutlet weak var lbl1: UILabel!
var str1: Double?
var str2: Double?

var locationManager:CLLocationManager!

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
determineMyCurrentLocation()

}


func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()

if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error) -> Void in

if (error != nil) {
print("ERROR:" + error!.localizedDescription)

return
}

if (placemarks?.count)! > 0 {
let pm = placemarks![0] as CLPlacemark
self.displayLocationInfo(placemark: pm)
} else {
print("Error with data")

}
})
}
func displayLocationInfo(placemark: CLPlacemark) {
// self.locationManager.stopUpdatingLocation()

print(placemark.locality)
print(placemark.postalCode)
print(placemark.administrativeArea)
print(placemark.country)
print(placemark.location)

}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}

@IBAction func currentadd(_ sender: Any) {


}

最佳答案

首先确保您已在 Info.plist 中添加了其中一个键

NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription

其次,您需要在 viewDidLoadviewDidAappear 中调用 defineMyCurrentLocation 方法。您还可以根据需要从任何按钮或事件调用 defineMyCurrentLocation

Edit

我想建议的另一件事是,如果您不想经常使用位置服务,您应该在 didUpdateLocations 中调用 manager.stopUpdatingLocation()

更新方法

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let managerLocation = manager.location{
CLGeocoder().reverseGeocodeLocation(managerLocation) { (placemarks, error) in
if let locations = placemarks ,let location = locations.first {
self.displayLocationInfo(placemark: location)
}else if let error = error{
print("ERROR:" + error.localizedDescription)
}
}
}
}

关于ios - 如何通过单击 uibutton 获取标签中的用户纬度和经度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54741177/

24 4 0