2017-07-06 125 views
3

我正在研究一個應用程序,其中有66個註釋。這些註釋是地區的中心,每當用戶輸入一個地區時,都會顯示一條通知,但僅適用於其中的20個,因爲地區監控的數量有限。我的問題是我不知道如何監控20多個地區。誰能幫忙?如何監控20多個地區?

回答

1

設置currentLocationdidUpdateLocations

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

+0

我在哪裏把這樣:var currentLocation:CLLocation { didSet { evaluateClosestRegions() }} – andre

+0

@andre您應就其採用'cllocationmanagerdelegate'協議類的屬性。基本上你得到'didUpdateLocation'回調的是同一個類。 – Honey

+0

我做到了,但函數evaluateClosestRegions永遠不會被調用 – andre

3

使用Apples API無法監視超過20個區域。

您必須將主動監測區域更新到最近的20個區域。

每當你進入/離開一個區域:

  • 檢查輸入的位置
  • 停止監視所有地區
  • 開始監控最近的19個地區(以輸入的位置距離),再加上進入一個。

如果結果不令人滿意,您可能還需要監測重要的位置變化,以便有機會每隔500米更新監控區域,同時不要耗盡太多電量。

+0

是的,但我不知道該怎麼辦 – andre

+0

哪一點不明確? – shallowThought

+0

如何定義最近的區域並開始監視它們 – andre