AuthUserDefaults.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. /// The utility class to manage data storage in NSUserDefaults.
  17. class AuthUserDefaults {
  18. /// The name of the persistent domain in user defaults.
  19. private let persistentDomainName: String
  20. /// The backing NSUserDefaults storage for this instance.
  21. private let storage: UserDefaults
  22. static func storage(identifier: String) -> Self {
  23. return Self(service: identifier)
  24. }
  25. required init(service: String) {
  26. persistentDomainName = kPersistentDomainNamePrefix + service
  27. storage = UserDefaults()
  28. }
  29. func data(forKey key: String) -> Data? {
  30. guard let allData = storage.persistentDomain(forName: persistentDomainName)
  31. else { return nil }
  32. if let data = allData[key] as? Data {
  33. return data
  34. }
  35. return nil
  36. }
  37. func setData(_ data: Data, forKey key: String) {
  38. var allData = storage.persistentDomain(forName: persistentDomainName) ?? [:]
  39. allData[key] = data
  40. storage.setPersistentDomain(allData, forName: persistentDomainName)
  41. }
  42. func removeData(forKey key: String) {
  43. guard var allData = storage.persistentDomain(forName: persistentDomainName) else { return }
  44. allData.removeValue(forKey: key)
  45. storage.setPersistentDomain(allData, forName: persistentDomainName)
  46. }
  47. /// Clears all data from the storage.
  48. ///
  49. /// This method is only supposed to be called from tests.
  50. func clear() {
  51. storage.setPersistentDomain([:], forName: persistentDomainName)
  52. }
  53. }