NightscoutService.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //
  2. // NightscoutService.swift
  3. // Loop
  4. //
  5. // Created by Nate Racklyeft on 7/3/16.
  6. // Copyright © 2016 Nathan Racklyeft. All rights reserved.
  7. //
  8. import Foundation
  9. import NightscoutUploadKit
  10. // Encapsulates a Nightscout site and its authentication
  11. struct NightscoutService: ServiceAuthentication {
  12. var credentials: [ServiceCredential]
  13. let title: String = LocalizedString("Nightscout", comment: "The title of the Nightscout service")
  14. init(siteURL: URL?, APISecret: String?) {
  15. credentials = [
  16. ServiceCredential(
  17. title: LocalizedString("Site URL", comment: "The title of the nightscout site URL credential"),
  18. placeholder: LocalizedString("http://mysite.herokuapp.com", comment: "The placeholder text for the nightscout site URL credential"),
  19. isSecret: false,
  20. keyboardType: .URL,
  21. value: siteURL?.absoluteString
  22. ),
  23. ServiceCredential(
  24. title: LocalizedString("API Secret", comment: "The title of the nightscout API secret credential"),
  25. placeholder: nil,
  26. isSecret: false,
  27. keyboardType: .asciiCapable,
  28. value: APISecret
  29. )
  30. ]
  31. verify { _, _ in }
  32. }
  33. // The uploader instance, if credentials are present
  34. private(set) var uploader: NightscoutUploader? {
  35. didSet {
  36. uploader?.errorHandler = { (error: Error, context: String) -> Void in
  37. print("Error \(error), while \(context)")
  38. }
  39. }
  40. }
  41. var siteURL: URL? {
  42. if let URLString = credentials[0].value {
  43. return URL(string: URLString)
  44. }
  45. return nil
  46. }
  47. var APISecret: String? {
  48. return credentials[1].value
  49. }
  50. private(set) var isAuthorized: Bool = false
  51. mutating func verify(_ completion: @escaping (_ success: Bool, _ error: Error?) -> Void) {
  52. guard let siteURL = siteURL, let APISecret = APISecret else {
  53. completion(false, nil)
  54. return
  55. }
  56. self.uploader = NightscoutUploader(siteURL: siteURL, APISecret: APISecret)
  57. self.uploader?.checkAuth({ (error) in
  58. if let error = error {
  59. // self.isAuthorized = false
  60. completion(false, error)
  61. } else {
  62. // self.isAuthorized = true
  63. completion(true, nil)
  64. }
  65. })
  66. }
  67. mutating func reset() {
  68. credentials[0].value = nil
  69. credentials[1].value = nil
  70. isAuthorized = false
  71. uploader = nil
  72. }
  73. }