我有一个列表,其中填充了来自API的数据。所以基本上这个过程是这样的:
当用户打开应用程序时,我会这样做:
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 20
locationManager.startUpdatingLocation()
}然后在我的func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])中,我调用API来获取数据。
但问题是,func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])有时可以被调用5-6次,所以会有很多API调用,如果我只得到一个位置,那么我得到一个远离用户的位置的可能性很大。
对如何解决这个问题有什么想法吗?我基本上想要最好的位置,并尽可能少地进行API调用,最好是这样。
发布于 2016-09-01 03:41:55
基本上,如果你想避免在func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])中调用API,你需要考虑一些控制:
在received locations
horizontalAccuracy和distanceFilter values之间创建一个时间间隔
记住,你总是需要避免:
在启动locationManager)之前,避免locations
代码示例:
protocol MyLocationManagerDelegate {
func locationControllerDidUpdateLocation(location: CLLocation)
}
final class MyLocationManager: NSObject, CLLocationManagerDelegate {
var oldLocation: CLLocation?
let kTimeFilter = Double(10) //avoid locations for each kTimeFilter seconds
let kValidDistanceToOldLocation = Double(100) //avoid location less than kValidDistanceToOldLocation meters
var startDate: NSDate?
var delegate: MyLocationManagerDelegate?
func isValidLocation(newLocation newLocation: CLLocation?, oldLocation: CLLocation?) -> Bool {
// avoid nil locations
if newLocation == nil {
return false
}
//avoid invalid locations
if newLocation!.coordinate.latitude == 0 || newLocation!.coordinate.longitude == 0 {
return false
}
//avoid invalid locations
if (newLocation!.horizontalAccuracy < 0){
return false
}
if oldLocation != nil {
let distance = newLocation!.distanceFromLocation(oldLocation!)
if fabs(distance) < kValidDistanceToOldLocation {
return false
}
//avoid out-of-order location.
let secondsSinceLastPoint = newLocation!.timestamp.timeIntervalSinceDate(oldLocation!.timestamp)
if secondsSinceLastPoint < 0 || secondsSinceLastPoint < kTimeFilter {
return false
}
}
//avoid cached locations (before you start the locationManager)
let secondsSinceManagerStarted = newLocation!.timestamp.timeIntervalSinceDate(startDate!)
if secondsSinceManagerStarted < 0 {
return false
}
return true
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations.last
if isValidLocation(newLocation: newLocation, oldLocation:oldLocation) || oldLocation == nil {
self.delegate?.locationControllerDidUpdateLocation(newLocation!)
oldLocation = newLocation
}
}
}
class ViewController: UIViewController, MyLocationManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let location = MyLocationManager()
location.delegate = self
}
func locationControllerDidUpdateLocation(location: CLLocation) {
//Api Call
}
}https://stackoverflow.com/questions/39212373
复制相似问题