的iOS地理栅栏如何在区域内部监控时开始

问题描述:

我的问题是处理基本相同的一个位置:
iOS Geofence, how to handle when inside region when monitoring starts?的iOS地理栅栏如何在区域内部监控时开始

我需要一个斯威夫特3溶液。

我在Geofencing上使用了极好的raywenderlich教程,它在我的项目中工作时只需很少的定制。跨越地理栅栏边界时,我的应用完美响应。

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

我假设我需要在我的appDelegate使用

locationManager.requestState(for region: CLRegion) 

我遗漏的一部分是如何将我的geofenced区域加载为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]) 

...工作正常