使用[FIRRemoteConfig remoteConfig]无法获取Firebase服务器配置值的原因排查
我在iOS项目中使用Firebase Remote Config,遇到了一个奇怪的问题:fetchWithExpirationDuration:completionHandler:返回的状态是FIRRemoteConfigFetchStatusSuccess,调用activateFetched也返回了true,但当我读取[FIRRemoteConfig remoteConfig][@"greeting"].stringValue时,只能拿到本地默认值。我已经在Firebase控制台创建了名为"greeting"的参数,请问可能有哪些原因导致这个问题?
我的代码:
- (void)fetchFirebaseRemoteConfig { long expirationDuration = 43200; if ([FIRRemoteConfig remoteConfig].configSettings.isDeveloperModeEnabled) { expirationDuration = 0; } [[FIRRemoteConfig remoteConfig] fetchWithExpirationDuration:expirationDuration completionHandler:^(FIRRemoteConfigFetchStatus status, NSError *error) { if (status == FIRRemoteConfigFetchStatusSuccess && error == nil) { BOOL didApply = [[FIRRemoteConfig remoteConfig] activateFetched]; ALog("Did apply remote config OK: %d", didApply); } else { ALog(@"Error %@", error.localizedDescription); } }]; NSString *greeting = [FIRRemoteConfig remoteConfig][@"greeting"].stringValue; ALog(@"greeting: %@", greeting); }
异步执行顺序错误:这是最常见的问题!你读取
greeting的代码写在了fetchWithExpirationDuration的回调函数外部,而fetch和activate操作是异步执行的。也就是说,在fetch完成并激活新配置之前,你就已经读取了配置值,这时候拿到的自然还是旧的本地默认值。你需要把读取值的代码移到activateFetched成功的代码块内部,确保激活后再获取值:[[FIRRemoteConfig remoteConfig] fetchWithExpirationDuration:expirationDuration completionHandler:^(FIRRemoteConfigFetchStatus status, NSError *error) { if (status == FIRRemoteConfigFetchStatusSuccess && error == nil) { BOOL didApply = [[FIRRemoteConfig remoteConfig] activateFetched]; ALog("Did apply remote config OK: %d", didApply); // 移到这里读取值 NSString *greeting = [FIRRemoteConfig remoteConfig][@"greeting"].stringValue; ALog(@"greeting: %@", greeting); } else { ALog(@"Error %@", error.localizedDescription); } }];参数名称不匹配:仔细检查Firebase控制台中的参数名称是否和代码里的
"greeting"完全一致——Firebase Remote Config的参数名称是区分大小写的,而且不能有空格或拼写错误。比如Greeting、greet和greeting都是完全不同的参数。控制台参数未发布:在Firebase控制台修改完参数后,一定要点击右上角的发布按钮,否则新的配置不会推送到服务器。如果只是保存了参数但没发布,fetch到的还是旧的配置(或者没有配置)。
默认值与服务器值相同:如果你的本地默认值和控制台设置的服务器值完全一样,你可能会误以为拿到的是本地值。可以临时把本地默认值改成一个明显不同的字符串(比如
"local_default"),再测试看看是否能获取到服务器的新值。缓存残留问题:即使开启了开发者模式,有时候旧的缓存可能还会影响结果。你可以尝试卸载App后重新安装,或者在fetch前调用
[[FIRRemoteConfig remoteConfig] reset]重置配置,再重新执行fetch和激活操作。项目配置不匹配:确认你的App使用的
GoogleService-Info.plist文件是正确的项目文件,并且App的Bundle ID和Firebase控制台中注册的Bundle ID完全一致。如果连接的是错误的Firebase项目,自然获取不到你设置的参数。
内容的提问来源于stack exchange,提问作者Jmf

