问题描述
我正在开发一个有66个注释的应用程序.这些注释是区域的中心,每当用户输入区域时,都会出现一条通知,但该通知仅对其中的前20个有效,因为监视重传的次数有限.我的问题是我不知道如何监视20多个区域.有人可以帮忙吗?
I'm working on an app in which there are 66 annotations. These annotations are centers of regions and whenever user enters a region, a notification appears, but that works only for first 20 of them because there's a limited number on monitoring regoins. My problem is that I don't know how to monitor more than 20 regions. Could anyone help?
推荐答案
从您的didUpdateLocations
var currentLocation : CLLocation?{
didSet{
evaluateClosestRegions()
}
}
var allRegions : [CLRegion] = [] // Fill all your regions
现在计算并找到最接近您当前位置的区域,然后仅跟踪这些区域.
Now calculate and find the closest regions to your current location and only track those.
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
To avoid having the didSet
called too many times, I suggest you set the distanceFilter
appropriately (not too big so you would catch the region's callbacks too late and not too small so that you won't have redundant code running). Or as this answer suggests, just use startMonitoringSignificantLocationChanges
to update your currentLocation
这篇关于如何监视20多个区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!