问题
I've come up with some code that prints the address and postalcode of my location. This is done in the didupdatelocation function.
The only problem that I occur, is that every second this address get's updated by the "didupdatelocation" function. Because this is very battery ineffecient, I was looking for ways to use an interval but I couldn't find ways (also not on Google en stackoverflow) on how to do this.
Can anybody give me tips how I can do this in Swift?
回答1:
The answers of Rajeshkumar and Basir doesn't change much for the battery power, their delegate method is still called the same number of times per minute.
If you want to have a more efficient behavior, try to change the values of distanceFilter, desiredAccuracy, and activityType (You can find all you need here)
manager.distanceFilter = 50 // distance changes you want to be informed about (in meters)
manager.desiredAccuracy = 10 // biggest approximation you tolerate (in meters)
manager.activityType = .automotiveNavigation // .automotiveNavigation will stop the updates when the device is not moving
Also if you only need the location of the user when it changes significantly, you can monitor significantLocationChanges, can also work when your app is killed.
回答2:
Try this
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [Any]) {
var mostRecentLocation: CLLocation? = locations.last
print("Current location: \(mostRecentLocation?.coordinate?.latitude) \(mostRecentLocation?.coordinate?.longitude)")
var now = Date()
var interval: TimeInterval = lastTimestamp ? now.timeIntervalSince(lastTimestamp) : 0
if !lastTimestamp || interval >= 5 * 60 {
lastTimestamp = now
print("Sending current location to web service.")
}
}
回答3:
Swift 3 version of this answer
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var newLocation = locations.last!
var locationAge = -newLocation.timestamp.timeIntervalSinceNow
if locationAge > 5.0 {
return
}
if newLocation.horizontalAccuracy < 0 {
return
}
// Needed to filter cached and too old locations
var loc1 = CLLocation(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
var loc2 = CLLocation(latitude: newLocation.coordinate.latitude, longitude: newLocation.coordinate.longitude)
var distance: Double = loc1.distanceFromLocation(loc2)
self.currentLocation = newLocation
if distance > 20 {
//significant location update
}
//location updated
}
回答4:
If you want to save as much battery as possible you can use startMonitoringSignificantLocationChanges
instead of startUpdatingLocation
.
It will only notify you of changes over 500m and minimum interval of updates is 5 minutes.
You can read more from here.
回答5:
Try use
manager.pausesLocationUpdatesAutomatically = true
also try put biggest value on
manager.distanceFilter = value
来源:https://stackoverflow.com/questions/43066350/swift-how-can-i-make-less-didupdatelocation-calls