Get the user’s location

Asked

Viewed 414 times

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 user’s location Swift?

2 answers

0


First you need to add the Cllocationmanagerdelegate in your class Viewcontroller:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.