gpt4 book ai didi

ios - 如何更改 iOS 的位置权限消息?

转载 作者:行者123 更新时间:2023-11-28 07:21:36 25 4
gpt4 key购买 nike

我正在学习 iOS 开发并遇到了奇怪的问题。为了获得在 viewController 中使用位置的用户许可,我正在定义位置管理器并请求 requestWhenInUseAuthorization()

像这样:

class ViewController: UIViewController, CLLocationManagerDelegate {

let lm = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()
lm.requestWhenInUseAuthorization()
}
}

然后,在 plist 中,我为权限对话框设置了正确的文本,如下所示:

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>We need your location</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>We need your location</string>
<key>NSLocationUsageDescription</key>
<string>We need your location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location</string>

一切正常,直到我尝试更改权限对话框的文本。在 plist 中更改它后,我正在重新编译它,但应用程序没有任何变化,我收到的是旧文本的对话框。所以我的问题 - 我该如何改变它?附言Xcode 10.3 和 iOS 12.4

最佳答案

转到 ViewController.swift 文件并添加以下行以导入 CoreLocation 框架。

import CoreLocation

使 ViewController 类符合 CLLocationManagerDelegate 协议(protocol)。将类声明行更改为

class ViewController: UIViewController, CLLocationManagerDelegate {
Add the following property

let locationMgr = CLLocationManager()

CLLocationManager 是将为您提供 GPS 坐标的对象。接下来,实现 getLocation(_:) 方法。

@IBAction func getLocation(_ sender: Any) {
// 1
let status = CLLocationManager.authorizationStatus()

switch status {
// 1
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
return

// 2
case .denied, .restricted:
let alert = UIAlertController(title: "Location Services disabled", message: "Please enable Location Services in Settings", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)

present(alert, animated: true, completion: nil)
return
case .authorizedAlways, .authorizedWhenInUse:
break

}

// 4
locationManager.delegate = self
locationManager.startUpdatingLocation()
}

authorizationStatus 返回当前的授权状态。

使用时授权在应用程序处于前台时获取位置更新

当禁用位置服务时,将向用户显示警告

将位置更新发送给委托(delegate),即 View Controller 。

接下来,实现 CLLocationManager 委托(delegate)方法。

  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let currentLocation = locations.last {
print("Current location: \(currentLocation)")
}
}


func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}

当前位置打印到控制台。

无法更新位置时会生成并显示错误。

要在应用程序运行时启用位置更新权限,需要一个特殊的 key 。打开 info.plist。右键单击并选择添加行。输入以下值。

In Info.plist
<key>NSLocationWhenInUse</key>
<string>This app needs access to your Location</string>

构建并运行项目,当应用请求权限时

关于ios - 如何更改 iOS 的位置权限消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57851148/

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