AuthUserDefaults.swift 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. required init(service: String) {
  23. persistentDomainName = kPersistentDomainNamePrefix + service
  24. storage = UserDefaults()
  25. }
  26. func data(forKey key: String) -> Data? {
  27. guard let allData = storage.persistentDomain(forName: persistentDomainName)
  28. else { return nil }
  29. if let data = allData[key] as? Data {
  30. return data
  31. }
  32. return nil
  33. }
  34. func setData(_ data: Data, forKey key: String) {
  35. var allData = storage.persistentDomain(forName: persistentDomainName) ?? [:]
  36. allData[key] = data
  37. storage.setPersistentDomain(allData, forName: persistentDomainName)
  38. }
  39. func removeData(forKey key: String) {
  40. guard var allData = storage.persistentDomain(forName: persistentDomainName) else { return }
  41. allData.removeValue(forKey: key)
  42. storage.setPersistentDomain(allData, forName: persistentDomainName)
  43. }
  44. /// Clears all data from the storage.
  45. ///
  46. /// This method is only supposed to be called from tests.
  47. func clear() {
  48. storage.setPersistentDomain([:], forName: persistentDomainName)
  49. }
  50. }