【问题标题】:startMonitoringForRegion not working, though implemented properlystartMonitoringForRegion 不工作,虽然实施得当
【发布时间】:2014-03-09 08:13:59
【问题描述】:

我一直在尝试让地理围栏工作,但似乎没有发生。

我得到了 didStartMonitoringForRegion 委托方法,但是 didEnterRegion 和 didExitRegion 没有在应该调用的时候被调用。如果我将模拟器设置为 1000 公里以外,我可以触发 didExitRegion,但显然这还不够准确。

我想我一定是没有正确实现它,所以我从本教程下载了源文件: http://code.tutsplus.com/tutorials/geofencing-with-core-location--mobile-15477

但是,我得到了完全相同的行为(didStartMonitoringForRegion 在实施时触发,但进入/退出没有),这让我认为我的问题不在于代码。我在开车时在模拟器和实际设备上都试过了,但它不起作用。

我无法弄清楚我错过了什么!

【问题讨论】:

  • 您是否在设备的设置中启用了后台应用刷新?另一个失败的原因是 cllocation manager 的委托,确保你有 location manager 的委托集,你在哪里实现了进入/退出。
  • 或者只是仔细检查您的 CLRegion。如果您从不从内到外或反向,您将永远不会被告知。

标签: ios core-location geofencing


【解决方案1】:

首先,您应该在要添加区域的类中实现此委托:

- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error

因此您可以知道某个位置是否注册失败(可能是因为您提供了无效的坐标,或者您超出了您的应用可以注册的最大区域数)。

其次,当你在模拟器上测试它时,你需要使用一个 GPX 文件来模拟你向一个区域移动,而不仅仅是改变模拟器的位置。

这里是一个用于走向曼哈顿中心的示例 gpx 文件:

<?xml version="1.0" encoding="UTF-8"?>
<gpx>
    <wpt lat="40.737181" lon="-73.98"></wpt>
    <wpt lat="40.733604" lon="-73.992110"></wpt>
</gpx>

它将开始缓慢地提供从航点 1 到航点 2 的模拟器位置更新。

您的航路点 1 应该在您正在监控的区域之外几英里处,理想情况下航路点 2 应该在它的中心。 您还可以在区域外添加第三个航路点,以便再次获得退出通知。

这不会立即生效,因为模拟器会模拟从航点到航点的驾驶/步行。您需要等待几秒钟才能收到通知。

最后作为提示,您需要检查您想要的半径是否超过操作系统允许的最大半径,这是我添加区域进行监控的实现:

- (void)registerRegionWithenterPoint:(CLLocationCoordinate2D)centerPoint regionRadius:(CLLocationDistance)radius andIdentifier:(NSString*)identifier {

    // If the radius is too large, registration fails automatically,
    // so clamp the radius to the max value.    
    if (radius > self.locationManager.maximumRegionMonitoringDistance)
        radius = self.locationManager.maximumRegionMonitoringDistance;

    // Create the region and start monitoring it.
    CLRegion* region = [[CLRegion alloc] initCircularRegionWithCenter:centerPoint radius:radius identifier:identifier];
    [self.locationManager startMonitoringForRegion:region desiredAccuracy:(kSystemVersion>=6)?400:100];
}

常量kSystemVersion 只是iOS 版本的常量,因为Apple 建议根据操作系统版本使用不同的准确度级别。

试试我的建议,看看你是否得到任何更新,但如果没有,请发布你的整个区域监控代码,因为你可能做错了什么,从你刚才说的我无法检测到

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    相关资源
    最近更新 更多