Skip to content
Permalink
Browse files
store 8 last points when loading data
  • Loading branch information
mackuba committed Jun 12, 2020
1 parent fdbdfc6 commit 319626dfb9c543dea38a3fb5fa64750204908608
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 17 deletions.
@@ -8,9 +8,15 @@
import Foundation

private let CurrentLevelKey = "CurrentLevel"
private let LastMeasurementDate = "LastMeasurementDate"
private let LastUpdateDate = "LastUpdateDate"
private let savedPointsKey = "SavedPoints"
private let lastUpdateDateKey = "LastUpdateDate"

private let pointsCount = 8

struct DataPoint {
let date: Date
let value: Double
}

class DataStore {
let defaults = UserDefaults.standard
@@ -19,28 +25,51 @@ class DataStore {

var currentLevel: Double? {
get {
return defaults.object(forKey: CurrentLevelKey) as? Double
return points.last?.value
}
set {
defaults.set(newValue, forKey: CurrentLevelKey)
}

var lastMeasurementDate: Date? {
get {
return points.last?.date
}
}

var lastUpdateDate: Date? {
get {
return defaults.object(forKey: LastUpdateDate) as? Date
return defaults.object(forKey: lastUpdateDateKey) as? Date
}
set {
defaults.set(newValue, forKey: LastUpdateDate)
defaults.set(newValue, forKey: lastUpdateDateKey)
}
}

var lastMeasurementDate: Date? {
var points: [DataPoint] {
get {
return defaults.object(forKey: LastMeasurementDate) as? Date
}
set {
defaults.set(newValue, forKey: LastMeasurementDate)
guard let tuples = defaults.object(forKey: savedPointsKey) as? [[Any]] else {
return []
}

return tuples.compactMap { t in
if t.count == 2, let date = t[0] as? Date, let value = t[1] as? Double {
return DataPoint(date: date, value: value)
} else {
return nil
}
}
}
}

func addPoints(_ newPoints: [DataPoint]) {
var pointMap: [Date:DataPoint] = [:]

self.points.forEach { p in pointMap[p.date] = p }
newPoints.forEach { p in pointMap[p.date] = p }

let allPoints = pointMap.keys.sorted().map { date in pointMap[date]! }
let recentPoints = Array(allPoints.suffix(pointsCount))
let encodedData = recentPoints.map { p in [p.date, p.value ]}

defaults.set(encodedData, forKey: savedPointsKey)
}
}
@@ -106,12 +106,13 @@ class KrakowPiosDataLoader {
if let data = data {
if let response = try? JSONDecoder().decode(Response.self, from: data) {
if let series = response.data.series.first {
if let point = series.points.last {
self.dataStore.currentLevel = point.value
self.dataStore.lastMeasurementDate = point.date
if let lastPoint = series.points.last {
self.dataStore.addPoints(
series.points.map({ DataPoint(date: $0.date, value: $0.value )})
)
self.dataStore.lastUpdateDate = Date()

NSLog("KrakowPiosDataLoader: saving data: %.0f at %@", point.value, "\(point.date)")
NSLog("KrakowPiosDataLoader: saving data: %.0f at %@", lastPoint.value, "\(lastPoint.date)")

success = true
}

0 comments on commit 319626d

Please sign in to comment.