requestWhenInUseAuthorization

requestWhenInUseAuthorization

我正在使用Swift编写适用于iOS 9.3的应用程序,并且需要一张 map 来显示用户位置。
我初始化CLLocationManager及其委托(delegate),然后配置info.plist
隐私-位置使用情况描述字符串,并调用requestWhenInUseAuthorization,但不显示任何授权请求。

这是我的代码:

import UIKit
import MapKit

class DetailController: UIViewController, CLLocationManagerDelegate {

    var locManager: CLLocationManager!

    @IBOutlet var myMap: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        mostraPosizione()
    }

    func mostraPosizione(){
        locManager = CLLocationManager()
        locManager.delegate = self
        locManager.desiredAccuracy = kCLLocationAccuracyBest

        let authorizationStatus = CLLocationManager.authorizationStatus()

        if (authorizationStatus == CLAuthorizationStatus.NotDetermined) {
            locManager.requestWhenInUseAuthorization()
        } else {
            locManager.startUpdatingLocation()
        }


        myMap.showsUserLocation = true
    }

    func locManager(manager: CLLocationManager,
    didChangeAuthorizationStatus status: CLAuthorizationStatus) {

        if (status == CLAuthorizationStatus.NotDetermined) {
            locManager.requestWhenInUseAuthorization()

        } else {
            locManager.startUpdatingLocation()
        }
    }
}

和我的info.plist中的屏幕截图
Swift requestWhenInUseAuthorization不起作用-LMLPHP

Xcode输出:



我正在iPhone 5 s(iOS 9.3)模拟器上对其进行测试。

这东西有什么问题?
有人有建议吗?

最佳答案

我认为是因为

let authorizationStatus = CLLocationManager.authorizationStatus()

nil,因此您的requestWhenInUseAuthorization()不会被调用。
  let authorizationStatus = CLLocationManager.authorizationStatus()

    if (authorizationStatus == CLAuthorizationStatus.NotDetermined) || (authorizationStatus == nil) {
        locManager.requestWhenInUseAuthorization()
    } else {
        locManager.startUpdatingLocation()
    }

应该工作。

编辑:

如果用户拒绝该请求,您也应该处理该案件
if (authorizationStatus == CLAuthorizationStatus.Denied ) {
  // Display a message, do what you want
}

实际上,一旦用户拒绝了授权,就无法再次显示弹出窗口,用户必须进入应用程序设置并自行设置使用其位置的授权。但是,您现在可以直接从您的应用程序链接到设置,因此对用户来说更容易。
// Open the settings of your app
if let url = NSURL(string:UIApplicationOpenSettingsURLString) {
    UIApplication.sharedApplication().openURL(url)
}

关于Swift requestWhenInUseAuthorization不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36972138/

10-12 00:29