如何访问用户坐标

时间:2017-11-24 23:42:28

标签: swift location maps

我正在尝试使用以下方式访问用户坐标:

import MapKit
import CoreLocation

override func viewDidLoad() {
    super.viewDidLoad()
    let locationManager = CLLocationManager()
    let userCoordinates = (locationManager.location?.coordinate)!
}

然而,它在模拟器加载时崩溃。我将模拟器位置设置为Apple,并将隐私密钥输入info.plist,但我不确定为什么这不是抓取用户位置。

1 个答案:

答案 0 :(得分:0)

在您开始使用设备的当前地理定位之前,首先需要做一些事情,并根据您提供的代码我假设您可能会遗漏一些,所以这里是一个使用Google Map的常见设置,基本上与其他任何一个一样:

class YourViewController: UIViewController, CLLocationManagerDelegate {

    // properties
    var locationManager = CLLocationManager()
    var currentCoordinate: CLLocationCoordinate2D?

    // load view
    override func loadView() {
        addLocationManager()
    }

    // add location manager
    func addLocationManager() {

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

    }

    // location manager delegate: did change authorization
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

        switch status {

        case .restricted:
            print("LOCATION ACCESS RESTRICTED")

        case .denied:
            print("LOCATION ACCESS DENIED")

        case .notDetermined:
            print("LOCATION ACCESS NOT DETERMINED")

        case .authorizedAlways:
            fallthrough

        case .authorizedWhenInUse:
            print("LOCATION STATUS GRANTED")

        }

    }


    // location manager delegate: did fail with error
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

        locationManager.stopUpdatingLocation()
        print("LOCATION ACCESS ERROR: \(error)")

    }


    // location manager delegate: did update locations
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let lastLocation = locations.last!

        // unhide map when current location is available
        if mapView.isHidden {
            mapView.camera = GMSCameraPosition.camera(withLatitude: lastLocation.coordinate.latitude, longitude: lastLocation.coordinate.longitude, zoom: 18, bearing: 0, viewingAngle: 0)
            mapView.isHidden = false
        }

        // update current location properties
        currentCoordinate = lastLocation.coordinate

    }


}

如果您已导入CoreLocation,则无需导入MapKit