我正在使用单例来从Firebase远程配置文件中获取参数。第一次运行应用程序时,我只能访问单例中的默认值;后续运行正确返回配置的值。什么是更好的方法,所以我可以从一个新的开始访问值?
protocol RemoteConfigProtocol {
func remoteConfigReceived()
}
class RemoteConfigManager {
static let sharedInstance = RemoteConfigManager()
var delegate: RemoteConfigProtocol?
let demoTitle: String
// private initialiser for the singleton
private init() {
// Configure for dev mode, if needed
let remoteConfig = RemoteConfig.remoteConfig()
#if DEBUG
let expirationDuration: TimeInterval = 0
remoteConfig.configSettings = RemoteConfigSettings(developerModeEnabled: true)!
#else
let expirationDuration: TimeInterval = 3600
#endif
// default values
let appDefaults: [String: NSObject] = [
"demo_title": "Default Title" as NSObject
]
remoteConfig.setDefaults(appDefaults)
// what exactly does "activeFetched" do, then?
remoteConfig.activateFetched()
// set the values
self.demoTitle = remoteConfig["demo_title"].stringValue!
// this seems to prep app for subsequent launches
remoteConfig.fetch(withExpirationDuration: expirationDuration) { status, _ in
print("Fetch completed with status:", status, "(\(status.rawValue))")
self.delegate?.remoteConfigReceived()
}
}
}
当异步fetch
命令在上面的代码中返回时(可能是参数值),我仍然无法访问来自配置文件的这些值。只有在应用程序的后续运行中,它们才会存在。这是为什么?我在代码中遗漏了什么吗?
答案 0 :(得分:0)
在获取完成后,您需要调用activateFetched()。现在,你在之前调用它甚至开始提取。在您调用activateFetched()之前,您的应用程序将无法使用提取的配置参数。
答案 1 :(得分:0)
使用@ doug-stevenson的回答,这是获取配置参数的代码,并立即使用它们:
protocol RemoteConfigProtocol {
func remoteConfigReceived()
}
class RemoteConfigManager {
static let sharedInstance = RemoteConfigManager()
var delegate: RemoteConfigProtocol?
var demoTitle: String
// private initialiser for the singleton
private init() {
// Configure for dev mode, if needed
let remoteConfig = RemoteConfig.remoteConfig()
#if DEBUG
let expirationDuration: TimeInterval = 0
remoteConfig.configSettings = RemoteConfigSettings(developerModeEnabled: true)!
#else
let expirationDuration: TimeInterval = 3600
#endif
// default values
let appDefaults: [String: NSObject] = [
"demo_title": "Default Title" as NSObject
]
remoteConfig.setDefaults(appDefaults)
// set the values from the defaults
self.demoTitle = remoteConfig["demo_title"].stringValue!
// fetch the new values
remoteConfig.fetch(withExpirationDuration: expirationDuration) { status, _ in
print("Fetch completed with status:", status, "(\(status.rawValue))")
// activate the newly fetched values
remoteConfig. activateFetched()
// reset my variables
self.demoTitle = remoteConfig["demo_title"].stringValue!
// tell my view controller to update the UI
self.delegate?.remoteConfigReceived()
}
}
}