Problems with swift 3 location

I want to make a simple iOS application using location data. Unfortunately, when testing both on the device and on the simulator, I get a “zero” even if I enter the debug code “Current Location” on the simulator. This is my first experience with CoreLocation in swift 3, so I used the same approach as before.

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var latitudeLabel: UILabel!
    @IBOutlet weak var longitudeLabel: UILabel!

    var locationManager:CLLocationManager?
    var currentLocation:CLLocation?

    override func viewDidLoad() {
        super.viewDidLoad()
        let locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
        updateLabels()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        self.currentLocation = locations[0]
    }

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

    func updateLabels() {
        latitudeLabel.text = String(describing: currentLocation?.coordinate.latitude)
        longitudeLabel.text = String(describing: currentLocation?.coordinate.longitude)
        print(currentLocation)
}

}

Of course, I wrote all the necessary secret keys in Info.plist.

When I try to print currentLocation, I get nil. With the last run, I found such a problem, but a warning appears, but disappears immediately

+4
source share
2 answers

viewDidLoad CLLocationManager , . , , , .

, , self.locationManager = locationManager. , , :

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager = CLLocationManager()
    locationManager?.delegate = self
    locationManager?.desiredAccuracy = kCLLocationAccuracyBest
    locationManager?.requestAlwaysAuthorization()
    locationManager?.startUpdatingLocation()
    // updateLabels()
}

, rmaddy, didUpdateLocations:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = locations.last, location.horizontalAccuracy >= 0 else { return }

    currentLocation = location
    updateLabels()
}
+4

updateLabels . locationManager(_:didUpdateLocations). , , updateLabels DispatchQueue.main.async.

+1

Source: https://habr.com/ru/post/1662903/


All Articles