gpt4 book ai didi

Swift requestWhenInUseAuthorization 不起作用

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:18 25 4
gpt4 key购买 nike

我正在使用 swift 为 iOS 9.3 编写一个应用程序,需要一张 map 来显示用户位置。我初始化 CLLocationManager 及其委托(delegate),我配置 info.plistPrivacy - Location Usage Description 字符串并调用 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()
}
}
}

还有一张来 self 的 info.plist 的截图 info.plist

Xcode 输出:

Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

我正在 iPhone 5s (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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com