使用用户位置时出错

时间:2018-06-22 23:39:15

标签: ios swift core-location

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

enter image description here

我在iPhone上进行了测试,我只是发布模拟器图像,供大家检查我得到了什么。

I tested on my IPhone, I'm just posting the simulator image for you guys check

1 个答案:

答案 0 :(得分:0)

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