iOS 地理围栏 监视开始时如何处理区域内



我的问题与这里的问题基本相同:
iOS地理围栏,监控开始时如何处理区域内?

我需要一个 Swift 3 解决方案。

我正在使用关于地理围栏的优秀 raywenderlich 教程,它在我的项目中工作,几乎没有自定义。 我的应用程序在跨越地理围栏边界时响应完美。

但我需要在应用程序启动时确定用户是否已经在地理围栏内。

我假设我需要使用

locationManager.requestState(for region: CLRegion)

在我的应用程序委托中。

我缺少的部分是如何将我的地理围栏区域加载为 CLRegion,以便我可以使用它在启动时调用该函数。

这是我尝试过的东西不起作用。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
...   //  There's some other stuff
   locationManager.delegate = self
   locationManager.requestAlwaysAuthorization()        
   loadAllGeotifications()  //  There will be only one !!
   let homeRegion = region(withGeotification: geotifications[1]) as! CLRegion
    locationManager.requestState(for: homeRegion)
    return true
}
func loadAllGeotifications() {
    geotifications = []
    guard let savedItems = UserDefaults.standard.array(forKey: PreferencesKeys.savedItems) else { return }
    for savedItem in savedItems {
        guard let geotification = NSKeyedUnarchiver.unarchiveObject(with: savedItem as! Data) as? Geotification else { continue }
            geotifications.append(geotification)
    }
}

func region(withGeotification geotification: Geotification) -> CLCircularRegion {
    let region = CLCircularRegion(center: geotification.coordinate, radius: geotification.radius, identifier: geotification.identifier)
    return region
   }
}
func locationManager(manager: CLLocationManager, didDetermineState state: CLRegionState, forRegion region: CLRegion) {
    let defaults: UserDefaults = UserDefaults.standard
    switch state {
    case .inside:
        defaults.set(true, forKey: "atHome")
    case .outside:
        defaults.set(false, forKey: "atHome")
    default:
        defaults.set(true, forKey: "atHome")   //  Assume user is at home unless/until determined otherwise
    }
}

didDetermineState永远不会回来。 无论 CLCircularRegion 是否被重新转换为 CLRegion 都是相同的问题 - 没有区别。

我解决了!

以下是解决问题的替换代码:

func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
... }

请注意在"管理器"之前添加"_"。

我的"atHome"标志现在在应用程序启动时已正确设置。

重新转换为 ULRegion 是可以的,但不是必需的。

let homeRegion = region(withGeotification: geotifications[1])

。工作正常

最新更新