首页 > 解决方案 > 使用用户位置时出错

问题描述

为什么我不能使用用户位置?我已经在 上添加了密钥Info.plist,但是当我运行该应用程序时,我没有收到该消息。可能会发生什么?

在此处输入图像描述

我在我的 iPhone 上进行了测试,我只是将模拟器图像发布给你们,看看我得到了什么。

我在我的iPhone上测试过,我只是发布模拟器图像供大家检查

标签: iosswiftcore-location

解决方案


将此添加到 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)")
}
}

推荐阅读