¿Cómo obtener el usuario de ubicación con CLLocationManager en poco tiempo?

Tengo este código en mi controlador de vista, pero esto no funciona:

import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { var location: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() location=CLLocationManager() location.delegate = self location.desiredAccuracy=kCLLocationAccuracyBest location.startUpdatingLocation() } func locationManager(location:CLLocationManager, didUpdateLocations locations:AnyObject[]) { println("locations = \(locations)") label1.text = "success" } 

Tengo los permisos de cómo leo en otra publicación. pero no obtengo nunca, no imprimo.

¡¡Gracias!!

primero agrega esta dos líneas en un archivo plist

1) NSLocationWhenInUseUsageDescription

2) NSLocationAlwaysUsageDescription

Entonces esta es la clase de trabajo completa implementar esto

 import UIKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate { var window: UIWindow? var locationManager: CLLocationManager! var seenError : Bool = false var locationFixAchieved : Bool = false var locationStatus : NSString = "Not Started" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { initLocationManager(); return true } // Location Manager helper stuff func initLocationManager() { seenError = false locationFixAchieved = false locationManager = CLLocationManager() locationManager.delegate = self locationManager.locationServicesEnabled locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() } // Location Manager Delegate stuff func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { locationManager.stopUpdatingLocation() if (error) { if (seenError == false) { seenError = true print(error) } } } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) { if (locationFixAchieved == false) { locationFixAchieved = true var locationArray = locations as NSArray var locationObj = locationArray.lastObject as CLLocation var coord = locationObj.coordinate println(coord.latitude) println(coord.longitude) } } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { var shouldIAllow = false switch status { case CLAuthorizationStatus.Restricted: locationStatus = "Restricted Access to location" case CLAuthorizationStatus.Denied: locationStatus = "User denied access to location" case CLAuthorizationStatus.NotDetermined: locationStatus = "Status not determined" default: locationStatus = "Allowed to location Access" shouldIAllow = true } NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil) if (shouldIAllow == true) { NSLog("Location to Allowed") // Start location services locationManager.startUpdatingLocation() } else { NSLog("Denied access: \(locationStatus)") } } } 

Los siguientes son los pasos simples para obtener la ubicación del usuario en Swift 3

1) Primero agrega esta línea en un archivo plist con descripción

  NSLocationWhenInUseUsageDescription 

2) Agregue CoreLocation.framework en su proyecto (en la sección Build Fases-> Link Binary With Library)

3) En la clase AppDelegate

  import CoreLocation 

4) Crear el objeto de locationManager de la siguiente manera

  var locationManager:CLLocationManager! 

5) Escriba el siguiente código en didFinishLaunchingWithOptions

  locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.distanceFilter = 200 locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() 

6) Confirme el delegado CLLocationManagerDelegate de la siguiente manera

  class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate 

7) Escriba el método de delegado CLLocationManagerDelegate para obtener la ubicación del usuario

 func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("location error is = \(error.localizedDescription)") } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let locValue:CLLocationCoordinate2D = (manager.location?.coordinate)! print("Current Locations = \(locValue.latitude) \(locValue.longitude)") } 

Ya que declara la ubicación como una opción opcional explícitamente desenvuelta (CLLocationManager!) Requiere un inicializador, ya sea en un método init como lo sugiere jhurray, o simplemente en línea, como:

 var location: CLLocationManager! = nil 

Tenga en cuenta que también tiene otros posibles problemas, incluido el hecho de que iOS 8 tiene nuevos requisitos para consultar al usuario el permiso para usar CoreLocation. Vea esta pregunta para más información.

Este es el mismo código que el anterior, pero se limpió para trabajar con Swift a partir de la fecha de esta publicación. Esto funcionó para mí.

Felicitaciones al cartel original.

(nota, pegue esto en cualquier clase que usará para manejar su ubicación).

 var lastLocation = CLLocation() var locationAuthorizationStatus:CLAuthorizationStatus! var window: UIWindow? var locationManager: CLLocationManager! var seenError : Bool = false var locationFixAchieved : Bool = false var locationStatus : NSString = "Not Started" override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.initLocationManager() } // Location Manager helper stuff func initLocationManager() { seenError = false locationFixAchieved = false locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() } // Location Manager Delegate stuff func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { locationManager.stopUpdatingLocation() if ((error) != nil) { if (seenError == false) { seenError = true print(error) } } } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { if (locationFixAchieved == false) { locationFixAchieved = true var locationArray = locations as NSArray var locationObj = locationArray.lastObject as CLLocation var coord = locationObj.coordinate println(coord.latitude) println(coord.longitude) } } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { var shouldIAllow = false switch status { case CLAuthorizationStatus.Restricted: locationStatus = "Restricted Access to location" case CLAuthorizationStatus.Denied: locationStatus = "User denied access to location" case CLAuthorizationStatus.NotDetermined: locationStatus = "Status not determined" default: locationStatus = "Allowed to location Access" shouldIAllow = true } NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil) if (shouldIAllow == true) { NSLog("Location to Allowed") // Start location services locationManager.startUpdatingLocation() } else { NSLog("Denied access: \(locationStatus)") } } 

Necesitas tener funciones de inicio.

Anula init (codificador 🙂 e init (nibName: bundle 🙂 y agrega cualquier init personalizado que desees.

Como ha dicho que la ubicación no es opcional, debe inicializarla antes de que su superinicio llame a TODAS sus funciones de inicio.

 func init() { ... location = CLLocationManager() // either set delegate and other stuff here or in viewDidLoad super.init(nibName:nil, bundle:nil) // other initialization below } 

Debe escribirse como func locationManager (administrador: CLLocationManager, didUpdateLocations ubicaciones: [CLLocation]) {

Haz lo siguiente en viewcontroller [Usando swift] –

  class ViewController: UIViewController,MKMapViewDelegate,CLLocationManagerDelegate { var locationManager: CLLocationManager? var usersCurrentLocation:CLLocationCoordinate2D? override func viewDidLoad() { super.viewDidLoad() self.locationManager = CLLocationManager() if CLLocationManager.authorizationStatus() == .NotDetermined{ locationManager?.requestAlwaysAuthorization() } locationManager?.desiredAccuracy = kCLLocationAccuracyBest locationManager?.distanceFilter = 200 locationManager?.delegate = self startUpdatingLocation() usersCurrentLocation = CLLocationCoordinate2DMake(LATTITUDE, LONGITUDE) let span = MKCoordinateSpanMake(0.005, 0.005) let region = MKCoordinateRegionMake(usersCurrentLocation!, span) mapview.setRegion(region, animated: true) mapview.delegate = self mapview.showsUserLocation = true } 

// MARK: CLLocationManagerDelegate métodos

 func startUpdatingLocation() { self.locationManager?.startUpdatingLocation() } func stopUpdatingLocation() { self.locationManager?.stopUpdatingLocation() } 

// MARK: MKMapViewDelegate

 func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){ mapview.centerCoordinate = userLocation.location!.coordinate mapview.showsUserLocation = true regionWithGeofencing() }