tutorial manager example corelocation ios swift mkmapview

ios - manager - Mostrar la ubicación actual y la ubicación de actualización en MKMapView en Swift



location manager swift tutorial (7)

Estoy aprendiendo a usar el nuevo lenguaje Swift (solo Swift, no Objective-C). Para hacerlo, quiero hacer una vista simple con un mapa (MKMapView). Quiero encontrar y actualizar la ubicación del usuario (como en la aplicación Apple Map).

Intenté esto, pero no pasó nada:

import MapKit import CoreLocation class MapView : UIViewController, CLLocationManagerDelegate { @IBOutlet weak var map: MKMapView! var locationManager: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() if (CLLocationManager.locationServicesEnabled()) { locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } } }

¿Me podría ayudar?


En Swift 4, utilicé la función de delegado de locationManager como se define arriba.

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

.. pero esto necesitaba ser cambiado a ...

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

Esto vino de .. https://github.com/lotfyahmed/MyLocation/blob/master/MyLocation/ViewController.swift - gracias!


Para Swift 2, debe cambiarlo a lo siguiente:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) self.map.setRegion(region, animated: true) }


Para Swift 3 y XCode 8, encuentro esta respuesta:

  • En primer lugar, debe establecer la privacidad en info.plist. Inserta la cadena NSLocationWhenInUseUsageDescription con tu descripción por qué quieres obtener la ubicación del usuario. Por ejemplo, configure la cadena "Para el mapa en la aplicación".

  • En segundo lugar, use este ejemplo de código

    @IBOutlet weak var mapView: MKMapView! private var locationManager: CLLocationManager! private var currentLocation: CLLocation? override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest // Check for Location Services if CLLocationManager.locationServicesEnabled() { locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() } } // MARK - CLLocationManagerDelegate func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { defer { currentLocation = locations.last } if currentLocation == nil { // Zoom to user location if let userLocation = locations.last { let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000) mapView.setRegion(viewRegion, animated: false) } } }

  • En tercer lugar, configure el indicador de Ubicación del usuario en el guión gráfico para mapView.


debe sobrescribir CLLocationManager.didUpdateLocations

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let userLocation:CLLocation = locations[0] as CLLocation locationManager.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) }

también tiene que agregar NSLocationWhenInUseUsageDescription y NSLocationAlwaysUsageDescription a su configuración de plist Result como valor


MyLocation es una demostración de Swift iOS.

Puede usar esta demostración para lo siguiente:

  1. Muestra la ubicación actual.

  2. Elija otra ubicación: en este caso, detenga el seguimiento de la ubicación.

  3. Agregue un alfiler en un MKMapView (iOS) al tocar.


CLLocationManager.didUpdateLocations sobrescribir CLLocationManager.didUpdateLocations (parte de CLLocationManagerDelegate) para recibir una notificación cuando el administrador de ubicación recupera la ubicación actual:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.last{ let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) self.map.setRegion(region, animated: true) } }

NOTA: Si su objetivo es iOS 8 o superior, debe incluir la clave NSLocationAlwaysUsageDescription o NSLocationWhenInUseUsageDescription en su Info.plist para que los servicios de ubicación funcionen.


100% de trabajo, pasos fáciles y probados

Importar bibliotecas:

import MapKit import CoreLocation

establecer delegados:

CLLocationManagerDelegate,MKMapViewDelegate

Tomar variable:

let locationManager = CLLocationManager()

escriba este código en viewDidLoad ():

self.locationManager.requestAlwaysAuthorization ()

// For use in foreground self.locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startUpdatingLocation() } mapView.delegate = self mapView.mapType = .standard mapView.isZoomEnabled = true mapView.isScrollEnabled = true if let coor = mapView.userLocation.location?.coordinate{ mapView.setCenter(coor, animated: true) }

Escriba el método de delegado para la ubicación:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let locValue:CLLocationCoordinate2D = manager.location!.coordinate mapView.mapType = MKMapType.standard let span = MKCoordinateSpanMake(0.05, 0.05) let region = MKCoordinateRegion(center: locValue, span: span) mapView.setRegion(region, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = locValue annotation.title = "Javed Multani" annotation.subtitle = "current location" mapView.addAnnotation(annotation) //centerMap(locValue) }

No olvides establecer permisos en info.plist

<key>NSLocationWhenInUseUsageDescription</key> <string>This application requires location services to work</string> <key>NSLocationAlwaysUsageDescription</key> <string>This application requires location services to work</string>

Se ve así: