我可以在应用程序工作于前台时扫描信标,但不能在后台工作。我在İnfo.plist和后台模式“位置更新”中添加了“隐私-始终且在使用时位置用法说明”和“隐私-处于使用时的位置用法说明”
func initScanBeacon() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways {
if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
if CLLocationManager.isRangingAvailable() {
startScanning()
}
}
}
}
func startScanning() {
let uuid = UUID(uuidString: "xxxxx")!
let beaconRegion = CLBeaconRegion(proximityUUID: uuid, major: 0, minor: 0, identifier: "xxxxx")
locationManager.startMonitoring(for: beaconRegion)
locationManager.startRangingBeacons(in: beaconRegion)
}
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
if beacons.count > 0 {
//print
} else {
}
}
默认情况下,移至后台后,iOS应用程序将不会继续在多个信标范围内移动信标。即使您从用户那里获得“始终”的位置使用许可并设置locationManager.allowsBackgroundLocationUpdates = true
,也是如此。
您可以采取多种技巧将背景范围扩大到几秒钟。有关详细信息,请参见我的详细答案here