To let your users opt-in or opt-out of using Firebase Performance Monitoring , you might want to configure your app so that you can enable and disable Performance Monitoring . You might also find this capability to be useful during app development and testing.
Ниже представлены некоторые варианты, которые стоит рассмотреть:
Вы можете отключить SDK Performance Monitoring при сборке приложения, с возможностью повторного включения во время выполнения.
Вы можете собрать приложение с включенным SDK Performance Monitoring но у вас есть возможность отключить его во время выполнения с помощью Firebase Remote Config .
Вы можете полностью отключить SDK Performance Monitoring , без возможности его включения во время выполнения.
Отключите Performance Monitoring в процессе сборки приложения.
One situation where disabling Performance Monitoring during your app build process could be useful is to avoid reporting performance data from a pre-release version of your app during app development and testing.
Чтобы отключить или деактивировать Performance Monitoring , вы можете добавить один из двух ключей в файл списка свойств ( Info.plist ) для вашего приложения Apple:
Чтобы отключить Performance Monitoring , но разрешить приложению включать его во время выполнения, установите
firebase_performance_collection_enabledвfalseв файлеInfo.plistвашего приложения.Чтобы полностью отключить Performance Monitoring без возможности его включения во время выполнения, установите
firebase_performance_collection_deactivatedвtrueв файлеInfo.plistвашего приложения.
Отключите приложение во время выполнения с помощью Remote Config
Firebase Remote Config lets you make changes to the behavior and appearance of your app, so it provides an ideal way to let you disable Performance Monitoring in deployed instances of your app.
To disable Performance Monitoring data collection the next time that your Apple app starts, use the example code shown below. For more information about using Remote Config in an Apple app, see Use Firebase Remote Config on Apple platforms .
Убедитесь, что в вашем
Podfileиспользуется Remote Config :pod 'Firebase/RemoteConfig'Добавьте следующий код в начало файла
AppDelegateвашего приложения:Быстрый
Примечание: Данный продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.import FirebaseRemoteConfigObjective-C
Примечание: Данный продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.@import FirebaseRemoteConfig;В файле
AppDelegateдобавьте следующий код в операторыlaunchOptionsв методе экземпляраapplication:didFinishLaunchingWithOptions:Быстрый
Примечание: Данный продукт недоступен для macOS, Mac Catalyst и watchOS.remoteConfig = RemoteConfig.remoteConfig() // You can change the "false" below to "true" to permit more fetches when validating // your app, but you should change it back to "false" or remove this statement before // distributing your app in production. let remoteConfigSettings = RemoteConfigSettings(developerModeEnabled: false) remoteConfig.configSettings = remoteConfigSettings! // Load in-app defaults from a plist file that sets perf_disable to false until // you update values in the Firebase console. remoteConfig.setDefaultsFromPlistFileName("RemoteConfigDefaults") // Important! This needs to be applied before FirebaseApp.configure() if !remoteConfig["perf_disable"].boolValue { // The following line disables all automatic (out-of-the-box) monitoring Performance.sharedInstance().isInstrumentationEnabled = false // The following line disables all custom monitoring Performance.sharedInstance().isDataCollectionEnabled = false } else { Performance.sharedInstance().isInstrumentationEnabled = true Performance.sharedInstance().isDataCollectionEnabled = true } // Use Firebase library to configure APIs FirebaseApp.configure()Objective-C
Примечание: Данный продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.self.remoteConfig = [FIRRemoteConfig remoteConfig]; // You can change the NO below to YES to permit more fetches when validating // your app, but you should change it back to NO or remove this statement before // distributing your app in production. FIRRemoteConfigSettings *remoteConfigSettings = [[FIRRemoteConfigSettings alloc] initWithDeveloperModeEnabled:NO]; self.remoteConfig.configSettings = remoteConfigSettings; // Load in-app defaults from a plist file that sets perf_disable to false until // you update values in the Firebase console. [self.remoteConfig setDefaultsFromPlistFileName:@"RemoteConfigDefaults"]; // Important! This needs to be applied before [FIRApp configure] if (!self.remoteConfig[@"perf_disable"].numberValue.boolValue) { // The following line disables all automatic (out-of-the-box) monitoring [FIRPerformance sharedInstance].instrumentationEnabled = NO; // The following line disables all custom monitoring [FIRPerformance sharedInstance].dataCollectionEnabled = NO; } else { [FIRPerformance sharedInstance].instrumentationEnabled = YES; [FIRPerformance sharedInstance].dataCollectionEnabled = YES; } // Use Firebase library to configure APIs [FIRApp configure];В
ViewController.mили другом файле реализации, используемом вашим приложением, добавьте следующий код для получения и активации значений Remote Config :Быстрый
Примечание: Данный продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.//RemoteConfig fetch and activation in your app, shortly after startup remoteConfig.fetch(withExpirationDuration: TimeInterval(30.0)) { (status, error) -> Void in if status == .success { print("Config fetched!") self.remoteConfig.activateFetched() } else { print("Config not fetched") print("Error \(error!.localizedDescription)") } }Objective-C
Примечание: Данный продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.//RemoteConfig fetch and activation in your app, shortly after startup [self.remoteConfig fetchWithExpirationDuration:30.0 completionHandler:^(FIRRemoteConfigFetchStatus status, NSError *error) { if (status == FIRRemoteConfigFetchStatusSuccess) { NSLog(@"Config fetched!"); [self.remoteConfig activateFetched]; } else { NSLog(@"Config not fetched"); NSLog(@"Error %@", error.localizedDescription); } }];Чтобы отключить Performance Monitoring в консоли Firebase , создайте параметр perf_disable в проекте вашего приложения, а затем установите его значение равным
true.Если установить значение параметра perf_disable равным
false, Performance Monitoring останется включенным.
Отключить автоматический или пользовательский сбор данных можно отдельно.
Вы можете внести некоторые изменения в приведенный выше код и в консоли Firebase , чтобы отключить весь автоматический (по умолчанию) мониторинг отдельно от пользовательского мониторинга.
Добавьте следующий код в оператор
launchOptionsв методе экземпляраapplication:didFinishLaunchingWithOptions:(вместо кода, показанного выше для того же метода экземпляра):Быстрый
Примечание: Данный продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.remoteConfig = FIRRemoteConfig.remoteConfig() let remoteConfigSettings = FIRRemoteConfigSettings(developerModeEnabled: true) remoteConfig.configSettings = remoteConfigSettings! // Important! This needs to be applied before FirebaseApp.configure() if remoteConfig["perf_disable_auto"].boolValue { // The following line disables all automatic (out-of-the-box) monitoring Performance.sharedInstance().isInstrumentationEnabled = false } else { Performance.sharedInstance().isInstrumentationEnabled = true } if remoteConfig["perf_disable_manual"].boolValue { // The following line disables all custom monitoring Performance.sharedInstance().isDataCollectionEnabled = false } else { Performance.sharedInstance().isDataCollectionEnabled = true } // Use Firebase library to configure APIs FirebaseApp.configure()Objective-C
Примечание: Данный продукт Firebase недоступен для macOS, Mac Catalyst и watchOS.self.remoteConfig = [FIRRemoteConfig remoteConfig]; FIRRemoteConfigSettings *remoteConfigSettings = [[FIRRemoteConfigSettings alloc] initWithDeveloperModeEnabled:YES]; self.remoteConfig.configSettings = remoteConfigSettings; // Important! This needs to be applied before [FirebaseApp configure] if (self.remoteConfig[@"perf_disable_auto"].numberValue.boolValue) { // The following line disables all automatic (out-of-the-box) monitoring [FIRPerformance sharedInstance].instrumentationEnabled = NO; } else { [FIRPerformance sharedInstance].instrumentationEnabled = YES; } if (self.remoteConfig[@"perf_disable_manual"].numberValue.boolValue) { // The following line disables all custom monitoring [FIRPerformance sharedInstance].dataCollectionEnabled = NO; } else { [FIRPerformance sharedInstance].dataCollectionEnabled = YES; } // Use Firebase library to configure APIs [FirebaseApp configure];Выполните следующие действия в консоли Firebase :
- Чтобы отключить весь автоматический (по умолчанию) мониторинг, создайте параметр perf_disable_auto в проекте вашего приложения, а затем установите его значение равным
true. - Чтобы отключить весь пользовательский мониторинг, создайте параметр perf_disable_manual в проекте вашего приложения, а затем установите его значение равным
true.
- Чтобы отключить весь автоматический (по умолчанию) мониторинг, создайте параметр perf_disable_auto в проекте вашего приложения, а затем установите его значение равным