如何监控20多个区域?



我正在开发一个有 66 个注释的应用程序。这些注释是区域的中心,每当用户进入区域时,都会显示一条通知,但这仅适用于其中的前 20 个,因为监视 regoins 的数量有限。我的问题是我不知道如何监控 20 多个区域。谁能帮忙?

设置currentLocation从你的didUpdateLocations

var currentLocation : CLLocation?{
didSet{
evaluateClosestRegions()
}
}
var allRegions : [CLRegion] = [] // Fill all your regions

现在计算并找到离您当前位置最近的区域,并仅跟踪这些区域。

func evaluateClosestRegions() {
var allDistance : [Double] = []
//Calulate distance of each region's center to currentLocation
for region in allRegions{
let circularRegion = region as! CLCircularRegion
let distance = currentLocation!.distance(from: CLLocation(latitude: circularRegion.center.latitude, longitude: circularRegion.center.longitude))
allDistance.append(distance)
}
// a Array of Tuples
let distanceOfEachRegionToCurrentLocation = zip(allRegions, allDistance)
//sort and get 20 closest
let twentyNearbyRegions = distanceOfEachRegionToCurrentLocation
.sorted{ tuple1, tuple2 in return tuple1.1 < tuple2.1 }
.prefix(20)
// Remove all regions you were tracking before
for region in locationManager.monitoredRegions{
locationManager.stopMonitoring(for: region)
}
twentyNearbyRegions.forEach{
locationManager.startMonitoring(for: $0.0)
}
}

为了避免didSet被调用太多次,我建议您适当地设置distanceFilter(不要太大,这样您就会太晚捕获区域的回调,也不要太小,这样您就不会运行冗余代码(。或者正如这个答案所暗示的那样,只需使用startMonitoringSignificantLocationChanges来更新您的currentLocation

没有办法使用 Apple API 监控 20 多个区域。

您必须将主动监控的区域更新为最近的 20 个区域。

每当您进入/离开某个区域时:

  • 检查输入的位置
  • 停止监视所有区域
  • 开始监视最近的 19 个区域(到输入位置的距离(加上输入的区域。

如果结果不令人满意,您可能还希望监视重大位置更改,以便有机会每 ~500 米更新一次监视区域,同时不消耗太多电池。

简短干净的解决方案:

private var locations = [CLLocation]()
private var currentLocation: CLLocation? {
didSet {
evaluateClosestRegions()
}
}
private func distance(from location: CLLocation) -> Double {
return currentLocation.distance(from: location))
}
private func evaluateClosestRegions() {
locationManager.monitoredRegions.forEach {
locationManager.stopMonitoring(for: $0)
}
locations.sort {
distance(from: $0) < distance(from: $1)
}
locations.prefix(20).forEach {
...
}
}

最新更新