簡體   English   中英

iOS:當應用程序被 didEnterRegion 喚醒時,如何啟動更新位置?

[英]iOS: How to startUpdatingLocation when app is awaken by didEnterRegion?

我想做的事:iPhone 正在睡覺。 在后台位置管理器正在掃描信標區域。 如果此區域被識別,我的應用程序應啟動信標測距以驗證到信標的距離。 當區域離開時,信標測距應該停止。

所以這是我的代碼:


-(void)locationManager:(CLLocationManager *)manager
        didEnterRegion:(CLRegion *)region
{
    NSLog(@"********** Beacon Region entered: %@", region);

    self.locationManager.allowsBackgroundLocationUpdates = YES;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.locationManager startUpdatingLocation];

    [self doBeaconRanging:(CLBeaconRegion *)region];

}

-(void)locationManager:(CLLocationManager *)manager
       didRangeBeacons:(NSArray<CLBeacon *> *)beacons
              inRegion:(CLBeaconRegion *)region
{
    NSLog(@"locationManager didRangeBeacons inRegion.");
}

-(void)locationManager:(CLLocationManager *)manager
    didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations {

    NSLog(@"locationManager didUpdateLocations");
}

-(void)locationManager:(CLLocationManager *)manager
         didExitRegion:(CLRegion *)region
{

    NSLog(@"********** Beacon Region left **********");

    [self.locationManager stopUpdatingLocation];

    NSSet *regions = [self.locationManager monitoredRegions];
    for(CLBeaconRegion *region in regions)
    {
        [self.locationManager stopRangingBeaconsInRegion:region];
    }
}

如果在應用程序處於前台時輸入區域,這可以正常工作。 didEnterRegion 被觸發並且信標測距開始。 即使我將應用程序和 iPhone 發送到睡眠狀態,信標測距也會繼續進行(只是為了測試,在實際應用程序中,我將在大約 3 分鍾后停止信標測距)。

但是當在 iPhone 被鎖定時觸發 didEnterRegion 時,行為是不同的。 位置更新和信標測距開始,但僅適用於 ca。 10 秒。 10 秒后,iPhone 重新進入睡眠狀態,位置更新和信標測距停止。 當我喚醒應用程序時,位置更新會立即開始,信標也會開始測距。 但當然,我不想喚醒應用程序。 一切都應該在后台運行,無需打開應用程序。

如果我在應用程序處於前台時開始位置更新並且從不停止它,那么一切正常。 即使在后台數小時后,位置更新也會一直出現。 但我認為由於電池壽命,這不是解決方案。

當應用程序處於后台時觸發 didEnteredRegion 時,如何開始更新位置?

默認情況下,信標測距更新在 iOS 的后台被阻止,除了以下事件之一之后的前 10 秒:

  1. 過渡到背景
  2. 監控進入/退出事件(例如地理圍欄或信標區域進入退出事件)
  3. 屏幕上的事件(如果啟用了信標監控,並且受監控區域的 notifyEntryStateOnDisplay 設置為 true)。

除了上述之外,還可以通過啟動后台任務將這些事件之一之后允許的后台測距時間從 10 秒延長到 30 秒(iOS 12 及更早版本為 180 秒)。

最后,您可以通過在 Info.plist 中額外聲明位置背景模式並使用 CoreLocation 調用startUpdatingLocation將 30 秒延長到無限期。 使用 GPS 時,位置更新的 3 公里精度足以無限期地保持測距而不會燒毀電池。

請注意,如果您確實在 Info.plist 中聲明了后台位置,則可能無法獲得 AppStore 的批准,除非您正在構建看似導航應用程序。 另請注意,恆定的背景測距將消耗大量電池,盡管小於恆定的 GPS 使用量。

您可以在我的博客文章中閱讀有關執行這些選項的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM