How to use Firebase RemoteConfig

Issue #493

Declare in Podfile

1
2
pod 'Firebase/Core'
pod 'Firebase/RemoteConfig'

Use RemoteConfigHandler to encapsulate logic. We introduce Key with CaseIterable and defaultValue of type NSNumber to manage default values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import Firebase
import FirebaseRemoteConfig

final class RemoteConfigHandler {
let remoteConfig: RemoteConfig

enum Key: String, CaseIterable {
case interval = "fetch_interval"

var defaultValue: NSNumber {
switch self {
case .periodicGetSalons: return NSNumber(value: 300)
}
}
}

init() {
self.remoteConfig = RemoteConfig.remoteConfig()

let settings = RemoteConfigSettings()
settings.minimumFetchInterval = 0
self.remoteConfig.configSettings = settings

let map = Key.allCases.reduce([String: NSObject](), { map, key in
var map = map
map[key.rawValue] = key.defaultValue
return map
})

self.remoteConfig.setDefaults(map)
}

func update() {
self.remoteConfig.fetchAndActivate(completionHandler: { status, error in
print(status, error as Any)
})
}

var fetchInterval: TimeInterval {
return getValue(key: .interval, transform: { $0.doubleValue })
}

private func getValue<T>(key: Key, transform: (NSNumber) -> T) -> T {
let number = remoteConfig.configValue(forKey: key.rawValue).numberValue ?? key.defaultValue
return transform(number)
}
}

Comments