ios - 使用用户位置时出错
问题描述
为什么我不能使用用户位置?我已经在 上添加了密钥Info.plist
,但是当我运行该应用程序时,我没有收到该消息。可能会发生什么?
我在我的 iPhone 上进行了测试,我只是将模拟器图像发布给你们,看看我得到了什么。
解决方案
将此添加到 info.plist 文件中
<key>NSLocationAlwaysUsageDescription</key>
<string>Application needs permission to access your current location.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Application needs permission to access your current location.</string>
并使用以下代码获取您的位置
class MapViewController: UIViewController, CLLocationManagerDelegate{
var locationManager = CLLocationManager()
var currentLocation: CLLocation?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager.distanceFilter = 10
locationManager.startUpdatingLocation()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingHeading()
}
// Handle incoming location events.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.last!
print("Location: \(location)")
}
// Handle authorization for the location manager.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
print("Location access was restricted.")
case .denied:
print("User denied access to location.")
case .notDetermined:
print("Location status not determined.")
case .authorizedAlways: fallthrough
case .authorizedWhenInUse:
print("Location status is OK.")
}
}
// Handle location manager errors.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
locationManager.stopUpdatingLocation()
print("Error: \(error)")
}
}
推荐阅读
- python - python/kivy:需要函数clock()但由于递归而崩溃
- c# - C# 将属性复制到输出目录设置为始终从 Nuget 用于 PackageReference 项目
- python - 如何从熊猫系列中的字符串中删除最后5个字符
- c++ - CImg 库编译时返回未定义的引用 `__imp_SetDIBitsToDevice'
- node.js - 巨大的 CSV 数据显示在 ChartJS
- php - 为什么我的捕获异常代码不起作用?
- javascript - 使用 jQuery 获取相关的 div 文本
- firebase - 在firestore中,如果我指定文档和字段,是否可以检索字段的数据类型?
- javascript - Javascript 绘制模式
- reactjs - 高阶组件中的类型推断