AppGroupSource.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import Combine
  2. import Foundation
  3. struct AppGroupSource: GlucoseSource {
  4. func fetch() -> AnyPublisher<[BloodGlucose], Never> {
  5. guard let suiteName = Bundle.main.appGroupSuiteName,
  6. let sharedDefaults = UserDefaults(suiteName: suiteName)
  7. else {
  8. return Just([]).eraseToAnyPublisher()
  9. }
  10. return Just(fetchLastBGs(60, sharedDefaults)).eraseToAnyPublisher()
  11. }
  12. private func fetchLastBGs(_ count: Int, _ sharedDefaults: UserDefaults) -> [BloodGlucose] {
  13. guard let sharedData = sharedDefaults.data(forKey: "latestReadings") else {
  14. return []
  15. }
  16. let decoded = try? JSONSerialization.jsonObject(with: sharedData, options: [])
  17. guard let sgvs = decoded as? [AnyObject] else {
  18. return []
  19. }
  20. var results: [BloodGlucose] = []
  21. for sgv in sgvs.prefix(count) {
  22. guard
  23. let glucose = sgv["Value"] as? Int,
  24. let direction = sgv["direction"] as? String,
  25. let timestamp = sgv["DT"] as? String,
  26. let date = parseDate(timestamp)
  27. else { continue }
  28. results.append(
  29. BloodGlucose(
  30. sgv: glucose,
  31. direction: BloodGlucose.Direction(rawValue: direction),
  32. date: Decimal(Int(date.timeIntervalSince1970 * 1000)),
  33. dateString: date,
  34. unfiltered: nil,
  35. filtered: nil,
  36. noise: nil,
  37. glucose: glucose,
  38. type: "sgv"
  39. )
  40. )
  41. }
  42. return results
  43. }
  44. private func parseDate(_ timestamp: String) -> Date? {
  45. // timestamp looks like "/Date(1462404576000)/"
  46. guard let re = try? NSRegularExpression(pattern: "\\((.*)\\)"),
  47. let match = re.firstMatch(in: timestamp, range: NSMakeRange(0, timestamp.count))
  48. else {
  49. return nil
  50. }
  51. let matchRange = match.range(at: 1)
  52. let epoch = Double((timestamp as NSString).substring(with: matchRange))! / 1000
  53. return Date(timeIntervalSince1970: epoch)
  54. }
  55. func sourceInfo() -> [String: Any]? {
  56. [GlucoseSourceKey.description.rawValue: "Group ID: \(Bundle.main.appGroupSuiteName ?? "Not set"))"]
  57. }
  58. }
  59. public extension Bundle {
  60. var appGroupSuiteName: String? {
  61. object(forInfoDictionaryKey: "AppGroupID") as? String
  62. }
  63. }