Swift 2 – 不能用CLLocationManager获取用户位置

这是我的VC代码:

import UIKit import MapKit import CoreLocation class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet weak var mapView: MKMapView! let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.requestWhenInUseAuthorization() mapView.showsUserLocation = true } func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { mapView.showsUserLocation = (status == .AuthorizedAlways) } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let locValue:CLLocationCoordinate2D = manager.location!.coordinate print("locations = \(locValue.latitude) \(locValue.longitude)") } } 

我还在我的plist文件中添加了NSLocationWhenInUseUsageDescription。 我有CoreLocation和MapKit框架,任何想法,为什么这不起作用? 它不显示用户在地图上的位置,也不打印出用户的坐标。 在堆栈溢出上没有find任何东西。

这对我有用

Swift 2 – (Xcode 7.2.1)

ViewController.swift

 import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { var locationManager: CLLocationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.delegate = self locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { self.locationManager.stopUpdatingLocation() let latestLocation = locations.last let latitude = String(format: "%.4f", latestLocation!.coordinate.latitude) let longitude = String(format: "%.4f", latestLocation!.coordinate.longitude) print("Latitude: \(latitude)") print("Longitude: \(longitude)") } } 

info.plist中

添加一个新行

信息属性列表: NSLocationWhenInUseUsageDescription

types:string

价值:应用程序使用这些信息来显示你的位置

尝试通过获取方法locationManager(_:,didUpdateLocations locations: [CLLocations])数组locations的最后一个对象来locationManager(_:,didUpdateLocations locations: [CLLocations])

像这样的东西:

 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let locValue:CLLocationCoordinate2D = locations.last! print("locations = \(locValue.latitude) \(locValue.longitude)") }