didUpdateLocations在swift中被多次调用3
问题描述:
didUpdateLocations被调用很多次。所以我如何处理停止这一点。我尝试使用didUpdateLocations中的locationManager.stopUpdatingLocation(),但它不能正常工作。didUpdateLocations在swift中被多次调用3
override func viewDidLoad()
{
super.viewDidLoad()
//for Authorisation from the User.
isAuthorizedtoGetUserLocation()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
func isAuthorizedtoGetUserLocation() {
if CLLocationManager.authorizationStatus() != .authorizedWhenInUse {
locationManager.requestWhenInUseAuthorization()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationManager.stopUpdatingLocation()
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
let camera = GMSCameraPosition.camera(withLatitude: locValue.latitude, longitude: locValue.longitude, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
self.view = mapView
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: locValue.latitude, longitude: locValue.longitude)
marker.title = "name"
marker.map = mapView
}
Udated代码错误
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
manager.stopUpdatingLocation()
manager = nil // Here it is giving error "Cannot assign to value: 'manager' is a 'let' constant"
var newLocation: CLLocation? = locations.last
var locationAge: TimeInterval? = -(newLocation?.timestamp.timeIntervalSinceNow)!
if Double(locationAge!) > 5.0 {
return
}
if Double((newLocation?.horizontalAccuracy)!) < 0 {
return
}
//manager = nil
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
let camera = GMSCameraPosition.camera(withLatitude: locValue.latitude, longitude: locValue.longitude, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
self.view = mapView
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: locValue.latitude, longitude: locValue.longitude)
marker.title = "name"
marker.map = mapView
}
答
您需要设置CLLocation经理distanceFilter属性如下:
/* Notify changes when device has moved x meters.
* Default value is kCLDistanceFilterNone: all movements are reported.
*/
self.locationManager.distanceFilter = 10.0f; // you can change as per your require ment
你怎么确定startUpdatingLocation()被调用一次以上?从代码的外观来看,每次加载视图时只应调用一次。 – dylanthelion
在这种情况下,这是预期的行为。该方法在由您的kCLLocationAccuracy确定的频率上被调用。请参阅@ anbu的答案,了解如何设置它。基本上,准确度越高,代表中调用的方法越频繁,手机使用的功率也越大(GPS可快速消耗电池电量)。 – dylanthelion