我希望我的应用显示用户的位置,但它不要求 WhenInUseAuthorization。我在 Info.plist 中添加了 NSLocationWhenInUseUsageDescription 键。我在具有模拟位置的 iOS 模拟器中以及在实际设备上进行了尝试。
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if CLLocationManager.authorizationStatus() == .NotDetermined {
self.locationManager.requestWhenInUseAuthorization()
}
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
let userLocation = CLLocationCoordinate2DMake(locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude)
mapView.region = MKCoordinateRegionMakeWithDistance(userLocation, 100, 100)
} else {
let defaultLocation = CLLocationCoordinate2DMake(45.5017, -73.5673)
mapView.region = MKCoordinateRegionMakeWithDistance(defaultLocation, 100, 100)
}
}
}
最佳答案
这是我的错误,我在测试文件夹的 Info.plist 而不是主项目的 plist 中添加了 NSLocationWhenInUseUsageDescription 键。
关于ios - CoreLocation requestWhenInUseAuthorization() 在 Swift 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31664463/