Beacon detection in background from framework

人走茶凉 提交于 2019-12-12 01:37:23

问题


I have a framework which had all beacon detection logic and a sample app which sets up and tears down framework. I want to get region enter and exit notifications after app is killed. I am able to get notifications from app when logic is in app. But when the logic is in framework I don't get notifications. What am I doing wrong?

import UIKit
import CoreLocation

extension AppDelegate: CLLocationManagerDelegate {

    func registerForBeaconNotifications() {
        let locationManager = CLLocationManager()
        let region = CLBeaconRegion(proximityUUID: UUID(uuidString: "83f9daec-4cae-54f1-b64e-846f12345d05")!, major: 10, minor: 10, identifier: "iPhone 6 Beacon")

        locationManager.delegate = self
        region.notifyOnEntry = true
        region.notifyOnExit = true
        region.notifyEntryStateOnDisplay = true

        locationManager.startMonitoring(for: region)
        locationManager.startRangingBeacons(in: region)

        // Register for showing notification alerts
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: .alert, categories: nil))
    }

    func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
        let notification = UILocalNotification()

        switch state {
        case .inside:
            notification.alertBody = "Entered region"
            UIApplication.shared.presentLocalNotificationNow(notification)

        case .outside:
            notification.alertBody = "Exited region"
            UIApplication.shared.presentLocalNotificationNow(notification)

        default:
            notification.alertBody = "Region unknown"
            UIApplication.shared.presentLocalNotificationNow(notification)
        }
    }
}

回答1:


In order to prevent garbage collection which will stop monitoring, locationManager needs to be a class variable, and the initialization must take place inside a method. Like this:

let locationManager: CLLocationManager!

func registerForBeaconNotifications() {
    self.locationManager = CLLocationManager()
    ...


来源:https://stackoverflow.com/questions/39913085/beacon-detection-in-background-from-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!