问题
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