如何监视20多个区域?

and*_*dre 5 monitoring region ios swift

我正在开发一个包含66个注释的应用程序。这些注释是区域的中心,每当用户输入区域时,都会显示一条通知,但是该通知仅对其中的20个有效,因为区域监视的数量有限。我的问题是我不知道如何监视20多个区域。有人可以帮忙吗?

sha*_*ght 5

使用 Apples API 无法监控 20 多个区域。

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

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

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

如果结果不令人满意,您可能还想监控重要的位置变化,以便有机会每约 500 米更新一次监控区域,同时又不会消耗太多电池。


Hon*_*ney 5

currentLocation从你的设置didUpdateLocations

var currentLocation : CLLocation?{
    didSet{
        evaluateClosestRegions()
    }
}

var allRegions : [CLRegion] = [] // Fill all your regions
Run Code Online (Sandbox Code Playgroud)

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

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)
    }

}
Run Code Online (Sandbox Code Playgroud)

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