Вы можете использовать Firebase Remote Config для определения параметров в своем приложении и обновления их значений в облаке, что позволяет вам изменять внешний вид и поведение вашего приложения без распространения обновления приложения.
Библиотека Remote Config используется для хранения значений параметров по умолчанию в приложении, получения обновлённых значений параметров из бэкэнда Remote Config и управления доступом к полученным значениям в вашем приложении. Подробнее см. в разделе Стратегии загрузки Remote Config .
Шаг 1: Добавьте Firebase в свое приложение
Прежде чем использовать Remote Config , вам необходимо:
Зарегистрируйте свой проект C++ и настройте его для использования Firebase.
Если ваш проект C++ уже использует Firebase, значит, он уже зарегистрирован и настроен для Firebase.
Добавьте Firebase C++ SDK в свой проект C++.
Обратите внимание, что добавление Firebase в ваш проект C++ включает в себя задачи как в консоли Firebase , так и в вашем открытом проекте C++ (например, вы загружаете файлы конфигурации Firebase из консоли, а затем перемещаете их в свой проект C++).
Шаг 2: Добавьте Remote Config в свое приложение
Андроид
После добавления Firebase в ваше приложение:
Создайте приложение Firebase, передав среду JNI и Activity:
app = ::firebase::App::Create(::firebase::AppOptions(), jni_env, activity);
Инициализируйте библиотеку Remote Config , как показано:
::firebase::remote_config::Initialize(app);
iOS+
После добавления Firebase в ваше приложение:
Создайте приложение Firebase:
app = ::firebase::App::Create(::firebase::AppOptions());
Инициализируйте библиотеку Remote Config , как показано:
::firebase::remote_config::Initialize(app);
Шаг 3: Установите значения параметров приложения по умолчанию
Вы можете задать значения параметров приложения по умолчанию в объекте Remote Config , чтобы приложение вело себя так, как задумано, до того, как оно подключится к бэкэнду Remote Config , и чтобы значения по умолчанию были доступны, если на бэкэнде ничего не установлено.
Определите набор имен параметров и значений параметров по умолчанию, используя объект
ConfigKeyValue*
или объектConfigKeyValueVariant*
с размером массива.Если вы уже настроили значения параметров бэкэнда Remote Config , вы можете скачать файл, содержащий эти пары «ключ/значение», и использовать его для создания объекта
map
. Подробнее см. в разделе «Загрузка значений по умолчанию для шаблона Remote Config .Add these values to the Remote Config object using
SetDefaults()
.
Step 4: Get parameter values to use in your app
Now you can get parameter values from the Remote Config object. If you set values in the Remote Config backend, fetched them, and then activated them, those values are available to your app. Otherwise, you get the in-app parameter values configured using SetDefaults()
.
To get these values, call the method listed below that maps to the data type expected by your app, providing the parameter key as an argument:
Step 5: Set parameter values
- In the Firebase console , open your project.
- Select Remote Config from the menu to view the Remote Config dashboard.
- Define parameters with the same names as the parameters that you defined in your app. For each parameter, you can set a default value (which will eventually override the in-app default value) and conditional values. To learn more, see Remote Config parameters and conditions .
Step 6: Fetch and activate values
- To fetch parameter values from the Remote Config backend, call the
Fetch()
method. Any values that you set on the backend are fetched and cached in the Remote Config object. - To make fetched parameter values available to your app, call the
ActivateFetched()
Step 7: Listen for updates in real time
After you fetch parameter values, you can use real-time Remote Config to listen for updates from the Remote Config backend. Real-time Remote Config signals to connected devices when updates are available and automatically fetches the changes after you publish a new Remote Config version.
Real-time updates are supported by the Firebase C++ SDK v11.0.0+ and higher for Android and Apple platforms.
- In your app, call
AddOnConfigUpdateListener
to start listening for updates and automatically fetch any new or updated parameter values. The following example listens for updates and, whenActivate
is called, uses the newly fetched values to display an updated welcome message.
remote_config->AddOnConfigUpdateListener( [](firebase::remote_config::ConfigUpdate&& config_update, firebase::remote_config::RemoteConfigError remote_config_error) { if (remote_config_error != firebase::remote_config::kRemoteConfigErrorNone) { printf("Error listening for config updates: %d", remote_config_error); } // Search the `updated_keys` set for the key "welcome_message." // `updated_keys` represents the keys that have changed since the last // fetch. if (std::find(config_update.updated_keys.begin(), config_update.updated_keys.end(), "welcome_message") != config_update.updated_keys.end()) { remote_config->Activate().OnCompletion( [&](const firebase::Future& completed_future, void* user_data) { // The key "welcome_message" was found within `updated_keys` and // can be activated. if (completed_future.error() == 0) { DisplayWelcomeMessage(); } else { printf("Error activating config: %d", completed_future.error()); } }, nullptr); } });
The next time you publish a new version of your Remote Config , devices that are running your app and listening for changes will call the config update listener.
Следующие шаги
If you haven't already, explore the Remote Config use cases , and take a look at some of the key concepts and advanced strategies documentation, including: