-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathRemoteConfigViewController.swift
248 lines (219 loc) · 8.1 KB
/
RemoteConfigViewController.swift
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import FirebaseRemoteConfig
import FirebaseRemoteConfigSwift
class RemoteConfigViewController: UIViewController {
private var remoteConfig: RemoteConfig!
private var remoteConfigView: RemoteConfigView { view as! RemoteConfigView }
private let topLabelKey = "topLabelKey"
private let typedRecipeKey = "typedRecipeKey"
private let bottomLabelKey = "bottomLabelKey"
override func loadView() {
view = RemoteConfigView()
}
/// Convenience init for injecting Remote Config instances during testing
/// - Parameter remoteConfig: a Remote Config instance
convenience init(remoteConfig: RemoteConfig) {
self.init()
self.remoteConfig = remoteConfig
}
override func viewDidLoad() {
super.viewDidLoad()
configureNavigationBar()
setupRemoteConfig()
configureFetchButtonAction()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
fetchAndActivateRemoteConfig()
}
// MARK: - Firebase 🔥
// Add additional keys that are in the console to see them in the log after fetching the config.
struct QSConfig: Codable {
let topLabelKey: String
let bottomLabelKey: String
let freeCount: Int
}
/// Initializes defaults from `RemoteConfigDefaults.plist` and sets config's settings to developer mode
private func setupRemoteConfig() {
remoteConfig = RemoteConfig.remoteConfig()
// This is an alternative to remoteConfig.setDefaults(fromPlist: "RemoteConfigDefaults"))
do {
try remoteConfig.setDefaults(from: QSConfig(topLabelKey: "myTopLabel",
bottomLabelKey: "Buy one get one free!",
freeCount: 4))
} catch {
print("Failed to set Defaults.")
}
let settings = RemoteConfigSettings()
settings.minimumFetchInterval = 0
remoteConfig.configSettings = settings
remoteConfig.add { RemoteConfigUpdate, Error in
NSLog("Received Realtime Signal")
guard Error == nil else {
DispatchQueue.main.async {
self.displayError(Error)
}
return
}
if (RemoteConfigUpdate?.updatedKeys.contains("realtime_rc_changed_params") != nil) {
NSLog("Received realtime_rc_changed_params")
}
self.remoteConfig.activate() { changed, error in
guard error == nil else {
DispatchQueue.main.async {
self.displayError(error)
}
return
}
DispatchQueue.main.async {
self.updateUI()
}
}
}
}
/// Fetches and activates remote config values
@objc
private func fetchAndActivateRemoteConfig() {
remoteConfig.fetchAndActivate { status, error in
guard error == nil else { return self.displayError(error) }
print("Remote config successfully fetched & activated!")
do {
let qsConfig: QSConfig = try self.remoteConfig.decoded()
print(qsConfig)
} catch {
self.displayError(error)
return
}
DispatchQueue.main.async {
self.updateUI()
}
}
}
/// This method applies our remote config values to our UI
private func updateUI() {
remoteConfigView.topLabel.text = remoteConfig[decodedValue: "topLabelKey"]
updateJSONView()
if var bottomLabel: String = remoteConfig[decodedValue: "bottomLabelKey"],
let freeCount: Int = remoteConfig[decodedValue: "freeCount"],
freeCount > 1,
bottomLabel.contains("one") {
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
if let english = formatter.string(from: NSNumber(value: freeCount)) {
bottomLabel = bottomLabel.replacingOccurrences(of: "one free", with: "\(english) free")
}
remoteConfigView.bottomLabel.text = bottomLabel
}
}
// MARK: - Private Helpers
private func configureNavigationBar() {
navigationItem.title = "Firebase Config"
guard let navigationBar = navigationController?.navigationBar else { return }
navigationBar.prefersLargeTitles = true
navigationBar.titleTextAttributes = [.foregroundColor: UIColor.systemOrange]
navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.systemOrange]
}
private func configureFetchButtonAction() {
remoteConfigView.fetchButton.addTarget(
self,
action: #selector(fetchAndActivateRemoteConfig),
for: .touchUpInside
)
}
private func updateJSONView() {
let jsonView = remoteConfigView.jsonView!
let displayedJSON = jsonView.subviews
displayedJSON.forEach { label in
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
label.alpha = 0
}) { _ in
label.removeFromSuperview()
}
}
struct Recipe: Decodable, CustomStringConvertible {
var recipe_name: String
var ingredients: [String]
var prep_time: Int
var cook_time: Int
var instructions: [String]
var yield: String
var serving_size: Int
var notes: String
var description: String {
return "Recipe Name: \(recipe_name)\n" +
"Ingredients: \(ingredients)\n" +
"Prep Time: \(prep_time)\n" +
"Cook Time: \(cook_time)\n" +
"Instructions: \(instructions)\n" +
"Yield: \(yield)\n" +
"Serving Size: \(serving_size)\n" +
"Notes: \(notes)"
}
}
guard let recipe: Recipe = try? remoteConfig[typedRecipeKey].decoded() else {
print("Failed to decode JSON for \(typedRecipeKey)")
return
}
let lines = recipe.description.split(separator: "\n")
for (index, line) in lines.enumerated() {
let lineSplit = line.split(separator: ":")
let formattedKey = String(lineSplit[0])
let stringValue = String(lineSplit[1])
let attributedKey = NSAttributedString(
string: formattedKey,
attributes: [.foregroundColor: UIColor.secondaryLabel]
)
let attributedValue = NSAttributedString(
string: stringValue,
attributes: [.foregroundColor: UIColor.systemOrange]
)
let labelAttributedText = NSMutableAttributedString()
labelAttributedText.append(attributedKey)
labelAttributedText.append(attributedValue)
let label = UILabel()
label.attributedText = labelAttributedText
label.alpha = 0
label.sizeToFit()
jsonView.addSubview(label)
animateFadeIn(for: label, duration: 0.3)
let height = jsonView.frame.height
let step = height / CGFloat(lines.count)
let offset = height * 0.2 * 1 / CGFloat(lines.count)
let x: CGFloat = jsonView.frame.width * 0.05
let y: CGFloat = step * CGFloat(index) + offset
label.frame.origin = CGPoint(x: x, y: y)
}
}
private func animateFadeIn(for view: UIView, duration: TimeInterval) {
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseIn, animations: {
view.alpha = 1
})
}
}
extension UIViewController {
public func displayError(_ error: Error?, from function: StaticString = #function) {
guard let error = error else { return }
print("🚨 Error in \(function): \(error.localizedDescription)")
let message = "\(error.localizedDescription)\n\n Occurred in \(function)"
let errorAlertController = UIAlertController(
title: "Error",
message: message,
preferredStyle: .alert
)
errorAlertController.addAction(UIAlertAction(title: "OK", style: .default))
present(errorAlertController, animated: true, completion: nil)
}
}