RemoteViewController.swift 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // RemoteViewController.swift
  3. // LoopFollow
  4. //
  5. // Created by Jonas Björkert on 2024-07-19.
  6. // Copyright © 2024 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. import SwiftUI
  11. import HealthKit
  12. import Combine
  13. class RemoteViewController: UIViewController {
  14. private var cancellable: AnyCancellable?
  15. private var hostingController: UIHostingController<AnyView>?
  16. override func viewDidLoad() {
  17. super.viewDidLoad()
  18. cancellable = Storage.shared.remoteType.objectWillChange
  19. .sink { [weak self] _ in
  20. DispatchQueue.main.async {
  21. self?.updateView()
  22. }
  23. }
  24. updateView()
  25. }
  26. private func updateView() {
  27. let remoteType = Storage.shared.remoteType.value
  28. if let existingHostingController = hostingController {
  29. existingHostingController.willMove(toParent: nil)
  30. existingHostingController.view.removeFromSuperview()
  31. existingHostingController.removeFromParent()
  32. }
  33. if remoteType == .nightscout {
  34. let remoteView = TrioNightscoutRemoteView()
  35. hostingController = UIHostingController(rootView: AnyView(remoteView))
  36. } else if remoteType == .trc {
  37. let trioRemoteControlViewModel = TrioRemoteControlViewModel()
  38. let trioRemoteControlView = TrioRemoteControlView(viewModel: trioRemoteControlViewModel)
  39. hostingController = UIHostingController(rootView: AnyView(trioRemoteControlView))
  40. } else {
  41. hostingController = UIHostingController(rootView: AnyView(Text("Please select a Remote Type in Settings.")))
  42. }
  43. if let hostingController = hostingController {
  44. addChild(hostingController)
  45. view.addSubview(hostingController.view)
  46. hostingController.view.translatesAutoresizingMaskIntoConstraints = false
  47. NSLayoutConstraint.activate([
  48. hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  49. hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  50. hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
  51. hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  52. ])
  53. hostingController.didMove(toParent: self)
  54. }
  55. if remoteType == .nightscout, !ObservableUserDefaults.shared.nsWriteAuth.value {
  56. NightscoutUtils.verifyURLAndToken { error, jwtToken, nsWriteAuth in
  57. DispatchQueue.main.async {
  58. ObservableUserDefaults.shared.nsWriteAuth.value = nsWriteAuth
  59. }
  60. }
  61. }
  62. }
  63. deinit {
  64. cancellable?.cancel()
  65. }
  66. }