ios - CoreLocation requestWhenInUseAuthorization() 在 Swift 中不起作用

标签 ios swift cocoa-touch core-location

我希望我的应用显示用户的位置,但它不要求 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/

相关文章:

ios - 如何在 Swift 中从 C 向数组追加新的 String 元素

iphone - ios设置隐藏:NO at begin of a long method does not show on display

iOS:使用 UIImageView 进行动画

ios - 离开 AVFullScreenViewController 后屏幕不会旋转回纵向

ios - 通过指针从用户类检索数据

ios - JSONSerialization 中的选项[]

swift - 如何在 Xcode 8 中更改 UIAlertController 的背景

ios - 保留发送到释放的 UIViewController

cocoa-touch - 无法从我的应用程序中删除应用程序图像或启动图像?

iphone - 不需要时对 NSURLConnection 进行身份验证