受监视的区域不适用于KVO

时间:2018-10-28 10:17:44

标签: ios cllocationmanager key-value-observing geofencing

我的应用程序使用区域监视。它设置几个区域并动态更新。
通过清除所有监视区域并设置新区域来完成此操作。

我遇到的一个问题是清除受监视的区域不是立即完成的,而是稍后显然是在单独的线程中进行的,请参见here

由于受监视区域的数量限制为20,因此我必须等到属性monitoredRegions为空数组之后才能添加新区域。

我的想法是使用KVO在此属性更改时得到通知。这样做如下(简化版):

final class LocationManager: CLLocationManager {

    static let shared = LocationManager() // Instantiate the singleton

    private static var locationManagerKVOcontext = 0

    private override init () {
        super.init()

        addObserver(self, 
                    forKeyPath: #keyPath(monitoredRegions), 
                    options: [],
                    context: &LocationManager.locationManagerKVOcontext)
    }

    override func observeValue(forKeyPath keyPath: String?, 
                               of object: Any?, 
                               change: [NSKeyValueChangeKey : Any]?, 
                               context: UnsafeMutableRawPointer?) {
        guard context == &LocationManager.locationManagerKVOcontext else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
            return
        }
        guard keyPath == #keyPath(monitoredRegions) else { return }
        if monitoredRegions.isEmpty {
            stopMonitoringRegionsCompletionBlock?()
        }
    }

使用此代码,在使用#keyPath(monitoredRegions)时出现以下构建错误:

LocationManager.swift:71:30: 'monitoredRegions' is unavailable  
/CoreLocation.CLLocationManager:50:14: 'monitoredRegions' has been explicitly marked unavailable here

如果我将#keyPath(monitoredRegions)替换为“monitoredRegions“,则可以构建应用程序,因为编译器无法检查keyPath的有效性,但是未观察到monitoredRegions,即{{1} }不会被调用。

因此在我看来,无法观察func observeValue的键值。

我的问题是:

我的代码原则上是正确的还是有解决方法?

PS:我想我可以自己轮询该属性,但这似乎很丑。

修改:

我实施了轮询,以找到任何解决方案,并获得了一个数量级来清除监视区域所需的时间。
就我而言,清除所有监视区域需要0.2到1.4秒。这次肯定取决于要清除的区域数。

0 个答案:

没有答案