AuthUserDefaults.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. private let kPersistentDomainNamePrefix = "com.google.Firebase.Auth."
  16. /** @class AuthUserDefaults
  17. @brief The utility class to storage data in NSUserDefaults.
  18. */
  19. class AuthUserDefaults {
  20. /** @var _persistentDomainName
  21. @brief The name of the persistent domain in user defaults.
  22. */
  23. private let persistentDomainName: String
  24. /** @var _storage
  25. @brief The backing NSUserDefaults storage for this instance.
  26. */
  27. private let storage: UserDefaults
  28. static func storage(identifier: String) -> Self {
  29. return Self(service: identifier)
  30. }
  31. required init(service: String) {
  32. persistentDomainName = kPersistentDomainNamePrefix + service
  33. storage = UserDefaults()
  34. }
  35. func data(forKey key: String) throws -> Data? {
  36. guard let allData = storage.persistentDomain(forName: persistentDomainName)
  37. else { return nil }
  38. if let data = allData[key] as? Data {
  39. return data
  40. }
  41. return nil
  42. }
  43. func setData(_ data: Data, forKey key: String) throws {
  44. var allData = storage.persistentDomain(forName: persistentDomainName) ?? [:]
  45. allData[key] = data
  46. storage.setPersistentDomain(allData, forName: persistentDomainName)
  47. }
  48. func removeData(forKey key: String) throws {
  49. guard var allData = storage.persistentDomain(forName: persistentDomainName) else { return }
  50. allData.removeValue(forKey: key)
  51. storage.setPersistentDomain(allData, forName: persistentDomainName)
  52. }
  53. /** @fn clear
  54. @brief Clears all data from the storage.
  55. @remarks This method is only supposed to be called from tests.
  56. */
  57. func clear() {
  58. storage.setPersistentDomain([:], forName: persistentDomainName)
  59. }
  60. }