【问题标题】:Swift 4 locationManager didEnterRegion doesn't fire when user is in region on app launch当用户在应用程序启动区域时,Swift 4 locationManager didEnterRegion 不会触发
【发布时间】:2018-12-01 13:06:02
【问题描述】:

我正在尝试检测用户是否正在我的应用中输入特定区域。

如果应用启动然后进入该区域时用户不在特定区域,则此方法可以正常工作。

但如果用户在应用启动时处于特定区域,则不会触发“didEnterRegion”函数。

这是我的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    self.dbRef = Database.database().reference()
    self.mapView.delegate = self
    self.initLocationManager()
    guard let userLocation = locationManager.location?.coordinate else {return}
    self.userLocation = userLocation
    let region = MKCoordinateRegion(center: userLocation, latitudinalMeters: 1200, longitudinalMeters: 1200)
    mapView.setRegion(region, animated: true)
    self.getPlaces { (places) in
        self.places = places
        self.addAnnotationsToMap(places)
        if(CLLocationManager.authorizationStatus() == .authorizedAlways){
            if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self){
                for place in places{
                    self.startMonitoring(place)
                }
            }
        }
    }
}

func startMonitoring(_ place: Place){
    let region = CLCircularRegion(center: place.getCoordinate(), radius: 50, identifier: place.identifier)
    region.notifyOnEntry = true
    region.notifyOnExit = true
    locationManager.startMonitoring(for: region)
}

func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
    print("Entered Region : \(region.identifier)")
}

【问题讨论】:

    标签: ios swift core-location cllocationmanager clcircularregion


    【解决方案1】:

    顾名思义,这是预期行为,它仅在区域更广泛的交叉处触发。如果要确定用户是在区域内还是在区域外,请使用locationManager.requestState(for region: CLRegion),然后在委托函数locationManager(_:didDetermineState:for:)中接收结果

    要查询所有受监控的区域,请为locationManager.monitoredRegions 中的每个对象调用requestState(region)

    【讨论】:

    • 像一个魅力 xD 一样工作......我以前使用 locationManager.requestState(for region: CLRegion),但忘记实现委托功能......谢谢:)
    猜你喜欢
    • 2014-07-30
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多