【发布时间】:2021-09-28 01:07:31
【问题描述】:
我用 iBeacon 做了一个应用程序。
我决定使用 CoreLocation 和 Ranging。
但是,我认为测距消耗了太多能量。
作为测距的替代方法,我尝试使用监控。
然后,我剖析 Ranging 的使用能级和 Monitoring 的使用能级。
测距比监控多使用大约 2 个能源使用水平
结果:(测距等级:10/20,监控等级:8/20)
但是,Monitoring 不会立即调用 didExit 或 didDetermineState。
我希望我的应用具有实时测距功能。
我的解决方案:
- 监控开始
- 如果我进入监控区域,我会开始测距
- 如果我退出区域,测距结果为零,并停止测距
- 监控停止和启动。
监控不会立即调用 exit 或 determineState 方法。
但是,我发现停止和重新运行监控使我的应用程序具有实时性。
我认为该解决方案可以减少待机时的能耗。
而且它确实有效!
▼ 这是我的代码。
class Service: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate, CLLocationManagerDelegate{
private let constraint = CLBeaconIdentityConstraint(uuid: Constants.beaconUUID!,
major: Constants.beaconMajor,
minor: Constants.beaconMinor)
private let region = CLBeaconRegion(beaconIdentityConstraint:
CLBeaconIdentityConstraint(uuid: Constants.beaconUUID!,
major: Constants.beaconMajor,
minor: Constants.beaconMinor),
identifier: Constants.beaconIdentifier)
var locationManager: CLLocationManager!
override init() {
super.init()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
}
}
extension Service {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
if manager.authorizationStatus == .authorizedAlways {
region.notifyOnExit = true
region.notifyOnEntry = true
region.notifyEntryStateOnDisplay = true
manager.startMonitoring(for: region)
}
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
if state == .inside {
didEnterEvents(manager)
}
}
func locationManager(_ manager: CLLocationManager, didRange beacons: [CLBeacon], satisfying beaconConstraint: CLBeaconIdentityConstraint) {
if beacons.first == nil {
didExitEvents(manager)
stopAndRerunMonitoring(manager, for: region)
}
}
}
extension Service {
private func stopAndRerunMonitoring(_ manager: CLLocationManager, for region: CLRegion) {
print("reboot!")
manager.stopMonitoring(for: region)
manager.startMonitoring(for: region)
}
private func didEnterEvents(_ manager: CLLocationManager) {
print("inside")
manager.startRangingBeacons(satisfying: constraint)
}
private func didExitEvents(_ manager: CLLocationManager) {
print("outside")
manager.stopRangingBeacons(satisfying: constraint)
}
}
我知道我的解决方案很糟糕。
但我找不到任何其他解决方案。
Lz,你能找到其他更好的解决方案吗?
等:
- didEnter 和 didExit 调用了确定状态方法。
我需要在其他代码中调用 requestState() 方法。所以我在determineState方法中写了一个输入事件逻辑。 - 您需要实时吗?
是的,因为我会用信标制作安全系统。所以我的应用程序的要求是实时的。 我需要实时区域和更少的能源消耗。
【问题讨论】:
标签: ios swift core-location ibeacon