我有一个使用Firebase作为后端的应用程序,我遇到了挑战。在Firebase后端中,我试图将电池电量和充电状态存储到Firebase,以便如果设备正在充电,它将charging
更新为true
,并且如果用户正在使用该应用程序和电池电量我要输入的更改会在每次更改值时不断更新firebase ref。
到目前为止,这是我的代码,但是每次电池百分比或充电状态发生变化时,我都无法更新Firebase数据库。
class DeviceValues {
static let instance = DeviceValues()
var batteryLevel: Float {
return UIDevice.current.batteryLevel
}
var batteryState: UIDevice.BatteryState {
return UIDevice.current.batteryState
}
var deviceID: String?
var chargingStatus: Bool? = false
func declaration() {
UIDevice.current.isBatteryMonitoringEnabled = true
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: UIDevice.batteryStateDidChangeNotification, object: nil)
print("BATTERY STATE 2 \(batteryState)")
if let uuid = UIDevice.current.identifierForVendor?.uuidString {
print("UUID \(uuid)")
deviceID = uuid
}
}
@objc func batteryLevelDidChange(_ notification: Notification) {
print("BATTERY LEVEL \(batteryLevel)")
}
@objc func batteryStateDidChange(_ notification: Notification) {
print("BATTERY STATE \(batteryState)")
switch batteryState {
case .unplugged, .unknown:
chargingStatus = false
case .charging:
chargingStatus = true
case .full:
chargingStatus = false
print("charging or full")
}
}
}
数据源
func sendGeoTag(deviceData: DeviceValues, manager: CLLocationManager) -> Observable<GeoTag> {
return Observable<GeoTag>.create({ (observer) -> Disposable in
let id = self.storage.getCurrentChampion()?.id!
self.singleChampRef = Database.database().reference(forChampionId: id ?? "")
let disposable = Disposables.create {
self.singleChampRef?.removeAllObservers()
}
let block = { (snapshot: DataSnapshot) -> Void in
if let data = snapshot.value as? [String: AnyObject] {
let geoTag = GeoTag(dictionary: data as NSDictionary)
geoTag.championId = snapshot.key
if !disposable.isDisposed {
observer.onNext(geoTag)
}
}
print(deviceData.chargingStatus!)
let battery = [
"charging": deviceData.chargingStatus!,
"level": Int(deviceData.batteryLevel * 100),
] as [String : Any]
let coordinates = [
"accuracy" : Double(manager.location?.horizontalAccuracy ?? 0.0).rounded(toPlaces: 3),
"altitude": Double(manager.location?.altitude ?? 0.0).rounded(toPlaces: 7),
"heading" : manager.heading ?? 0.0,
"lat": Double(manager.location?.coordinate.latitude ?? 0.0).rounded(toPlaces: 7),
"lng": Double(manager.location?.coordinate.longitude ?? 0.0).rounded(toPlaces: 7),
"speed": manager.location?.speed ?? 0.0
] as [String : Any]
let post = [
"active" : false,
"battery": battery,
"coordinates" : coordinates,
"mock": false,
"online": false,
"timestamp": Double(manager.location?.timestamp.timeIntervalSince1970 ?? 0.0).rounded(toPlaces: 0)
] as [String : Any]
snapshot.ref.setValue(post)
}
self.singleChampRef?.observe(.childChanged, with: block)
return disposable
})
}