我正在开发一个有 66 个注释的应用程序。这些注释是区域的中心,每当用户进入一个区域时,都会出现一条通知,但这只适用于前 20 个区域,因为监视 regoins 的数量有限。我的问题是我不知道如何监控超过 20 个区域。谁能帮忙?
最佳答案
从你的 didUpdateLocations
设置 currentLocation
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
(不要太大,这样你会捕捉到区域的回调太晚而不是太晚)小,这样你就不会运行冗余代码)。或者作为 this answer建议,只需使用 startMonitoringSignificantLocationChanges
来更新您的 currentLocation
关于ios - 如何监控20多个区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44946411/