RemoteConfigValue.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2024 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 FirebaseCore
  15. import Foundation
  16. // TODO: Some objc's and public's should be removed.
  17. @objc(FIRRemoteConfigValue)
  18. public class RemoteConfigValue: NSObject, NSCopying {
  19. /// Data backing the config value.
  20. @objc public let dataValue: Data
  21. /// Identifies the source of the fetched value. Only for Firebase internal use.
  22. @objc public let source: RemoteConfigSource
  23. /// Designated initializer. Only for Firebase internal use.
  24. @objc public init(data: Data?, source: RemoteConfigSource) {
  25. dataValue = data ?? Data()
  26. self.source = source
  27. }
  28. /// Gets the value as a string.
  29. @objc public var stringValue: String {
  30. if let string = String(data: dataValue, encoding: .utf8) {
  31. return string
  32. }
  33. return "" // Return empty string if data is not valid UTF-8
  34. }
  35. /// Gets the value as a number value.
  36. @objc public var numberValue: NSNumber {
  37. return NSNumber(value: Double(stringValue) ?? 0)
  38. }
  39. /// Gets the value as a boolean.
  40. @objc public var boolValue: Bool {
  41. return (stringValue as NSString).boolValue
  42. }
  43. /// Gets a foundation object (NSDictionary / NSArray) by parsing the value as JSON.
  44. @objc(JSONValue) public var jsonValue: Any? {
  45. do {
  46. let jsonObject = try JSONSerialization.jsonObject(with: dataValue, options: [])
  47. return jsonObject
  48. } catch {
  49. RCLog.debug("I-RCN000065", "Error parsing data as JSON.")
  50. return nil
  51. }
  52. }
  53. /// Debug description showing the representations of all types.
  54. override public var debugDescription: String {
  55. let content = """
  56. Boolean: \(boolValue), String: \(stringValue), Number: \(numberValue), \
  57. JSON:\(String(describing: jsonValue)), Data: \(dataValue), Source: \(source.rawValue)
  58. """
  59. return "<\(type(of: self)): \(Unmanaged.passUnretained(self).toOpaque()), \(content)>"
  60. }
  61. /// Copy method.
  62. @objc public func copy(with zone: NSZone? = nil) -> Any {
  63. return RemoteConfigValue(data: dataValue, source: source)
  64. }
  65. }