我需要获得用户的当前位置,但是currentLocation返回alawas为零。然而,CLLocationManager.authorizationStatus是authorizedWhenInUse,在地图上,我位置的引脚是正确的。
import Foundation
import CoreLocation
class Location: NSObject, CLLocationManagerDelegate {
var currentLocation: CLLocation? = nil
var showUserLocation: Bool?
var isAuthorised = false {
didSet {
if isAuthorised {
locationManager.startUpdatingLocation()
showUserLocation = true
} else {
locationManager.stopUpdatingLocation()
currentLocation = nil
showUserLocation = false
}
}
}
private let locationManager = CLLocationManager()
override init() {
super.init()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLocation = locations.last
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
isAuthorised = (status == .authorizedWhenInUse)
}
func distance(of position: Position) -> CLLocationDistance {
let location = CLLocation(latitude: position.lat, longitude: position.lng)
return currentLocation?.distance(from: location) ?? Double.infinity
}
}
extension CLLocationCoordinate2D {
var position:Position {
return Position(lat: latitude, lng: longitude)
}
}谢谢!
编辑:我已经找到解决方案了!
在我的MapViewController中,我在插入Map之前加载了注释。因此,函数距离是在函数didUpdateLocations之前执行的。
我为失去的时间道歉..。非常感谢你的帮助。
发布于 2018-03-15 03:38:57
我编写了完整的代码,通过LocationManager类获取当前位置。此代码位于LocationManager.swift文件中。
LocationManager.swift
import Foundation
import CoreLocation
typealias LocationHandler = (_ location: CLLocation?, _ error: Error?) -> Void
class LocationManager: NSObject {
var locationManager: CLLocationManager?
var locationHandler: LocationHandler?
override init() {
super.init()
setupLocation()
}
fileprivate func setupLocation() {
locationManager = CLLocationManager()
locationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager?.distanceFilter = kCLLocationAccuracyBest
locationManager?.delegate = self
locationManager?.requestWhenInUseAuthorization()
}
public func findCurrentLocation(_ handler: LocationHandler?) {
if isLocationPermissionEnabled() {
locationHandler = handler
locationManager?.startUpdatingLocation()
}
}
}
extension LocationManager: CLLocationManagerDelegate {
public func isLocationPermissionEnabled() -> Bool {
let status = CLLocationManager.authorizationStatus()
return (status == .denied || status == .notDetermined) ? false : true
}
func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let currentLocation = locations.last {
self.locationHandler?(currentLocation, nil)
}
}
func locationManager(_: CLLocationManager, didFailWithError error: Error) {
self.locationHandler?(nil, error)
}
}https://stackoverflow.com/questions/49289565
复制相似问题