CAge.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // LoopFollow
  2. // CAge.swift
  3. import Foundation
  4. extension MainViewController {
  5. // NS Cage Web Call
  6. func webLoadNSCage() {
  7. let currentTimeString = dateTimeUtils.getDateTimeString()
  8. let parameters: [String: String] = [
  9. "find[eventType]": NightscoutUtils.EventType.cage.rawValue,
  10. "find[created_at][$lte]": currentTimeString,
  11. "count": "1",
  12. ]
  13. NightscoutUtils.executeRequest(eventType: .cage, parameters: parameters) { (result: Result<[cageData], Error>) in
  14. switch result {
  15. case let .success(data):
  16. self.updateCage(data: data)
  17. case let .failure(error):
  18. LogManager.shared.log(category: .nightscout, message: "webLoadNSCage, error: \(error.localizedDescription)")
  19. }
  20. }
  21. }
  22. // NS Cage Response Processor
  23. func updateCage(data: [cageData]) {
  24. infoManager.clearInfoData(type: .cage)
  25. if data.count == 0 {
  26. return
  27. }
  28. currentCage = data[0]
  29. let lastCageString = data[0].created_at
  30. let formatter = ISO8601DateFormatter()
  31. formatter.formatOptions = [.withFullDate,
  32. .withTime,
  33. .withDashSeparatorInDate,
  34. .withColonSeparatorInTime]
  35. Storage.shared.cageInsertTime.value = formatter.date(from: lastCageString)?.timeIntervalSince1970 as! TimeInterval
  36. if let cageTime = formatter.date(from: lastCageString)?.timeIntervalSince1970 {
  37. let now = dateTimeUtils.getNowTimeIntervalUTC()
  38. let secondsAgo = now - cageTime
  39. // let days = 24 * 60 * 60
  40. let formatter = DateComponentsFormatter()
  41. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  42. formatter.allowedUnits = [.day, .hour] // Units to display in the formatted string
  43. formatter.zeroFormattingBehavior = [.pad] // Pad with zeroes where appropriate for the locale
  44. if let formattedDuration = formatter.string(from: secondsAgo) {
  45. infoManager.updateInfoData(type: .cage, value: formattedDuration, numericValue: secondsAgo / 86400)
  46. }
  47. }
  48. }
  49. }