如何监控20多个地区?

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

从你的didUpdateLocations设置currentLocation

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

现在计算并find距离您当前位置最近的地区,并只跟踪这些地区。

 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调用次数太多,我build议你适当地设置distanceFilter (不要太大,以免太迟捕获区域的callback,不能太小,以免运行冗余代码)。 或者,正如这个答案build议,只需使用startMonitoringSignificantLocationChanges来更新您的currentLocation

使用Apples API无法监视超过20个区域。

您必须将主动监测的地区更新到最近的20个地区。

每当你进入/离开一个地区:

  • 检查input的位置
  • 停止监测所有地区
  • 开始监测最近的19个地区(到input地点的距离)加上input的地区。

如果结果不令人满意,您可能还需要监测重大的位置变化,以便有机会每500米更新监测区域,同时不要耗尽太多电量。