在UILabel上显示的经度和纬度

时间:2019-04-08 07:11:21

标签: swift geolocation uilabel

您好,我只需要一些帮助来检索用户位置的纬度和经度,并能够将其显示在UILabel上。 我是新手,很快就知道了,我知道如何接收这些值,因为我使用过void函数,但实际上显示它们才是让我着迷

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用核心位置执行以下操作

1。提供正确的说明

要收集位置更改数据,您需要在Info.plist文件中设置两个特殊字符串

Imahe

然后做

import CoreLocation

final class ViewController: UIViewController {

    @IBOutlet weak var coordinatesLabel: UILabel!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.requestAlwaysAuthorization()
        locationManager.delegate = self
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        locationManager.startUpdatingLocation()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        locationManager.stopUpdatingLocation()
    }
}

extension ViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        guard status == .authorizedAlways || status == .authorizedWhenInUse else {
            // Handle when no access
            return
        }
        manager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first?.coordinate else { return }
        coordinatesLabel.text = "Lat: \(location.latitude), Lng: \(location.longitude)"
    }
}