2017-07-12 162 views
2

我正在构建iOS应用程序,需要知道用户何时处于其家中20-30米的范围内。位置更新在后台停止 - iOS

我用户地理栅栏触发事件,当用户距离家中500米时,我使用CLLocationManager开始跟踪实际位置并检查到他们家的距离。

我的问题是,当我在应用程序处于后台时从我的geofence事件中调用“startUpdatingLocation”时,它只运行了20秒,然后停止提供任何回调。 如果我在20秒后打开应用程序并将其放回背景,那么它会一直给我回调,直到我停止。 如果我在应用程序运行时调用“startUpdatingLocation”,然后将其放入后台,它将保持正常运行状态。

我的初始化代码如下所示:

init(config: AutounlockConfiguration) { 
    super.init() 

    self.config = config 

    self.locationManager = CLLocationManager() 

    self.locationManager.requestAlwaysAuthorization() 
    self.locationManager.requestWhenInUseAuthorization() 

    self.locationManager.delegate = self 
    self.locationManager.pausesLocationUpdatesAutomatically = false 
    self.locationManager.allowsBackgroundLocationUpdates = true 
    self.locationManager.activityType = .automotiveNavigation 
    self.locationManager.distanceFilter = kCLDistanceFilterNone 
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation 
} 

,当我开始更新位置我不喜欢这样写道:

func startFetchingUserLocation() { 
    if (!isFetchingLocation) { 
     isFetchingLocation = true 
     DanaDebugger.presentDebugPushMessage(message: "fetching new location") 
     locationManager.startUpdatingLocation() 
    } 
} 

我启用了位置的背景模式,包括NSLocationAlwaysUsageDescription在我的info.plist文件中。 我真的不知道该从哪里出发,希望有人能够提供帮助。

回答

0
locationManager.startMonitoringSignificantLocationChanges() 

使用这条线,而不是此行

locationManager.startUpdatingLocation() 

它会解决你的问题

+0

或者同时使用;您可以在前台启用重要的位置更改。这将允许您在地理围栏中调用后台的'startUpdatingLocation'并获得持续更新。 – Paulw11

+0

非常感谢!这正是我需要的答案!现在运行完美。 –