CLLocationManager区域监视委托类问题

时间:2015-09-29 19:42:33

标签: ios swift core-location ibeacon

我已经围绕CoreLocation实现了一个自定义类来进行iBeacon区域监控。

这个类有一些自定义属性,我用它来存储一些与信标相关的信息供以后使用(在进入和退出事件期间)。

我面临的问题是当应用程序被终止或保存在后台时,这些存储的属性不再可用。我的意思是,让我们说应用程序在后台/终止时找到了一个信标区域,通常应用程序将在后台启动以供我们处理。我希望在此期间使用存储的属性进行自定义操作。

以前有人遇到过这个问题吗?我这样做是错误的吗?另外,我正在使用我目前正在工作的cocoapod库中的这个类。

以下是我写的课程。

 @available(iOS 9.0, *)
class BeaconManager: NSObject, CLLocationManagerDelegate {
   //these properties are becoming nil
   private var manager: CLLocationManager
   private var lastDetection: NSDate?
   private var isMonitoring = false
   private var repository: [String: DBeacon]
   private var monitoredRegions: [String: DBeacon] becoming nil
   private var notifyBackground = true

   static let sharedManager = BeaconManager()
   weak var delegate:BeaconProtocol?

   private override init() {
    manager = CLLocationManager()
    repository =  [:]
    monitoredRegions = [:]

    if CLLocationManager.authorizationStatus() != .AuthorizedAlways {
        manager.requestAlwaysAuthorization()
    }

    super.init()
    manager.delegate = self
}

func startMonitoringForBeacon(beacon: Beacon) throws {
    guard CLLocationManager.locationServicesEnabled() else {
        CFLogger.ERROR("Location services not enabled")
        throw BeaconErrorDomain.AuthorizationError(msg: "Location services not enabled")
    }

    guard CLLocationManager.authorizationStatus() == .AuthorizedAlways else {
        switch CLLocationManager.authorizationStatus() {
        case .Denied:
            throw BeaconErrorDomain.AuthorizationError(msg: "User denied location services")
        case .Restricted:
            throw BeaconErrorDomain.AuthorizationError(msg: "App is prevented from accessing Location Services")
        default:
            throw BeaconErrorDomain.AuthorizationError(msg: "App doesn't have authorization to monitor regions")
        }
    }

    guard CLLocationManager.isMonitoringAvailableForClass(CLBeaconRegion) else {
        CFLogger.ERROR("Region monitoring not available on this device")
        throw DBeaconKitErrorDomain.RegionMonitoringError(msg: "Region monitoring not available on this device")
    }


    guard let auuid = NSUUID(UUIDString: beacon.uuid) else {
        throw BeaconErrorDomain.InvalidUUIDString
    }

    let region:CLBeaconRegion!

    switch (beacon.major, beacon.minor) {
        case (.None, .None):
            region = CLBeaconRegion(proximityUUID: auuid, identifier: dbeacon.identifier)
        case (.Some(let major), .None):
            region = CLBeaconRegion(proximityUUID: auuid, major: UInt16(major), identifier: beacon.identifier)
        case (.Some(let major), .Some(let minor)):
            region = CLBeaconRegion(proximityUUID: auuid, major: UInt16(major), minor: UInt16(minor), identifier: beacon.identifier)
        default:
            throw BeaconErrorDomain.InvalidDBeaconInfo
    }

    region.notifyEntryStateOnDisplay = false
    region.notifyOnEntry = true
    region.notifyOnExit = true

    repository[beacon.identifier] = beacon
    manager.startMonitoringForRegion(region)
}

func stopMonitoringForBeacons(beacons: [Beacon]) {
    guard isMonitoring else {
        return
    }

    beacons.forEach { (dbeacon) -> () in
        stopMonitoringForBeacon(beacon)
    }
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    guard let handler = delegate else {
        return
    }

    handler.initializationFailed(error)
}

func locationManager(manager: CLLocationManager, didStartMonitoringForRegion region: CLRegion) {
    guard let aregion = region as? CLBeaconRegion, beacon = repository[aregion.identifier] else {
        return
    }

    isMonitoring = true

    monitoredRegions[aregion.identifier] = beacon
    manager.requestStateForRegion(region)
}

func locationManager(manager: CLLocationManager, monitoringDidFailForRegion region: CLRegion?, withError error: NSError) {
    guard let aregion = region as? CLBeaconRegion, beacon = repository[aregion.identifier], handler = delegate else {
        return
    }

    handler.monitoringFailedForRegion(beacon, error: error)
}

func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {
    guard let aregion = region as? CLBeaconRegion else {
        return
    }

    guard let beacon = monitoredRegions[aregion.identifier] else {
        return
    }

    guard let handler = delegate else {
     print("Handler not available to report beacon entry event \(region.identifier)")
        return
    }

    print("Entered beacon region \(beacon)")
    handler.entered(beacon)
}

func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) {
    guard let aregion = region as? CLBeaconRegion, beacon = monitoredRegions[aregion.identifier], handler = delegate else {
        print("Handler not available to report beacon exit event \(region.identifier)")
        return
    }

    print("Exited beacon region \(beacon)")
    handler.exited(beacon)
}
 }

我最终发现存储的属性没有我在启动区域监视时设置的值。

真正感谢任何帮助。

问候。

1 个答案:

答案 0 :(得分:1)

正如@ Paulw11所说,属性在应用程序重启时失去了初始化值。处理此问题的典型方法是将这些属性存储到NSUserDefaults中。下面的代码段显示了如何恢复init方法底部的lastDetection字段。必须调用另一个名为save()的方法,以便在更改后保留该字段。

private override init() {
    manager = CLLocationManager()
    repository =  [:]
    monitoredRegions = [:]

    if CLLocationManager.authorizationStatus() != .AuthorizedAlways {
        manager.requestAlwaysAuthorization()
    }

    super.init()
    manager.delegate = self

    let userDefaults = NSUserDefaults.standardUserDefaults()    
    lastDetection = userDefaults.valueForKey("last_detection") as! NSDate?

}

func save() {
    let userDefaults = NSUserDefaults.standardUserDefaults()    
    userDefaults.setValue(lastDetection, forKey: "last_detection")
}

上面的示例仅显示保存和恢复您的一个属性。您需要对所有这些执行此操作,并且有些处理会更复杂(例如monitoredRegionsrepository),因为它们是无法直接序列化为{{{}的复杂数据类型1}}。要执行此序列化,您可以尝试使用JSON将它们转换为可以存储的字符串,然后从同一个字符串中解析出来。