Pick up user location

1
class ViewController: UIViewController {

var locationManager = CLLocationManager()

@IBOutlet weak var meuMapa: MKMapView!
override func viewDidLoad() {
    // Ask for Authorisation from the User.
    self.locationManager.requestAlwaysAuthorization()

    // For use in foreground
    self.locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self //ERRO: Cannot assign value of type ‘ViewController’to type CLLocationManager
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()

How to get the location of the user Swift ?

    
asked by anonymous 26.09.2016 / 02:28

2 answers

0

First you need to add the CLLocationManagerDelegate in your ViewController class:

>
class ViewController: UIViewController, CLLocationManagerDelegate {

Then implement the didUpdateLocations method:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.last!
    print("Latitude: \(location.coordinate.latitude)")
    print("Longitude: \(location.coordinate.longitude)")
}
    
26.09.2016 / 04:03
0

In this and the user method know your location

import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBAction func LocalizaME (_ sender: AnyObject) {

        Manager.delegate = self
        Manager.desiredAccuracy = kCLLocationAccuracyBest
        Manager.requestWhenInUseAuthorization()
        Manager.startUpdatingLocation()

        MapView.showsUserLocation = true

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){

        let userlocation:CLLocation = locations [0] as CLLocation
        Manager.stopUpdatingLocation()

        let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)

        let span = MKCoordinateSpanMake (0.5, 0.5)

        let region = MKCoordinateRegion(center: location, span: span)

        MapView.setRegion(region, animated: true)
    }
}
    
11.10.2016 / 18:06