Уведомляйте тестировщиков о новых сборках


Дополнительные SDK Firebase App Distribution для iOS и Android позволяют отображать внутри приложения оповещения для тестировщиков о появлении новых сборок вашего приложения, доступных для установки. В этом руководстве объясняется, как использовать SDK App Distribution для iOS и Android для создания и настройки оповещений о новых сборках для ваших тестировщиков.

Прежде чем начать

If you haven't already, add Firebase to your iOS project .

Шаг 1 : Включите API средства тестирования App Distribution

  1. Select your project in the Google Cloud console .

  2. В разделе Firebase App Testers API нажмите «Включить» .

Шаг 2 : Добавьте App Distribution в ваше приложение.

  1. Open the Podfile you created for the project (or run pod init to create one), then add the following line inside the target section:

    pod 'FirebaseAppDistribution'
  2. In the directory of your podfile, run pod install , then open the created .xcworkspace file.

  3. Import the Firebase module in your App struct or UIApplicationDelegate :

    Быстрый

    import FirebaseCore
    import FirebaseAppDistribution
    

    Objective-C

    @import FirebaseCore;
    @import FirebaseAppDistribution;
    
  4. Configure a FirebaseApp shared instance in your app delegate's application(_:didFinishLaunchingWithOptions:) method:

    Быстрый

    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
    
  5. If swizzling is disabled, pass any opened URLs to the App Distribution SDK in your implementation of application(_:open:options:) :

    Быстрый

    func application(_ app: UIApplication, 
                     open url: URL,
                     options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
       if AppDistribution.appDistribution().application(application, open: url, options: options) {
          return true
       }
    
       // Handle other non-Firebase URLs here.
    
       return false
    }
    

    Objective-C

    - (BOOL)application:(UIApplication *)app 
                openURL:(NSURL *)url 
                options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
       if ([[FIRAppDistribution appDistribution] application:app openURL:url options:options]) {
          return YES;
       }
    
       // Handle other non-Firebase URLs here.
    
       return NO;
    }
    
  6. Наконец, перекомпилируйте ваше приложение.

Шаг 3 : Настройка оповещений в приложении

SDK App Distribution предоставляет два способа настройки оповещений о сборке приложения для ваших тестировщиков: базовая конфигурация оповещений, которая включает в себя предварительно созданные диалоги обновления приложения и входа в систему для отображения тестировщикам, и расширенная конфигурация оповещений, которая позволяет настраивать собственный пользовательский интерфейс. Мы рекомендуем сначала использовать базовую конфигурацию оповещений, если вы новичок в SDK App Distribution .

Базовая конфигурация

Используйте checkForUpdate , чтобы отобразить предварительно созданное диалоговое окно включения оповещений для тестировщиков, которые еще не включили оповещения, а затем проверить, доступна ли новая сборка. При вызове метод выполняет следующую последовательность действий:

  1. Проверяет, включены ли у тестировщика оповещения, предлагая ему войти в App Distribution с помощью своей учетной записи Google.

  2. If the tester has not yet enabled alerts, displays a pre-built dialogue.

    Включение оповещений — это одноразовая процедура на тестовом устройстве, которая сохраняется после обновлений вашего приложения. Оповещения остаются включенными на тестовом устройстве до тех пор, пока приложение не будет удалено или пока не будет вызван метод signOutTester . Дополнительную информацию см. в справочной документации по методу ( на Swift или Objective-C ).

  3. Checks for newly available builds for the tester to install.

Вы можете вызвать checkForUpdate() в любой точке вашего приложения. Например, вы можете предложить тестировщикам установить новые доступные сборки при запуске, включив checkForUpdate() в обработчик onAppear(perform:) корневого представления вашего приложения.

The following example checks whether or not the tester has enabled alerts and has access to a new build, and if so, displays a dialogue when the build is available to install:

Быстрый

Примечание: Данный продукт недоступен для операционных систем macOS, Mac Catalyst, tvOS и watchOS.
AppDistribution.appDistribution().checkForUpdate(completion: { release, error in
  if error != nil {
      // Handle error
      return
  }

  guard let release = release else {
    return
  }

  // Customize your alerts here.
  let title = "New Version Available"
  let message = "Version \(release.displayVersion)(\(release.buildVersion)) is available."
  let uialert = UIAlertController(title: title,message: message, preferredStyle: .alert)

  uialert.addAction(UIAlertAction(title: "Update", style: UIAlertAction.Style.default) {
    _ in
    UIApplication.shared.open(release.downloadURL)
  })
  uialert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) {
    _ in
  })

  // self should be a UIViewController.
  self.present(uialert, animated: true, completion: nil)
})

Objective-C

Note: This product is not available on macOS, Mac Catalyst, tvOS or watchOS targets.
[[FIRAppDistribution appDistribution]
  checkForUpdateWithCompletion:^(FIRAppDistributionRelease *_Nullable release,
                                 NSError *_Nullable error) {
  if (error) {
    // Handle error
    return;
  }

  if (release) {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"New Version Available"
message:[NSString stringWithFormat:@"Version %@ (%@) is available.", release.displayVersion,
release.buildVersion] preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *updateAction = [UIAlertAction actionWithTitle:@"Update"
style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
      [[UIApplication sharedApplication] openURL:release.downloadURL options:@{}
completionHandler:nil];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {}];
    [alert addAction:updateAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
  }
}];

Расширенная конфигурация

The methods signInTester() and isTesterSignedIn give you more flexibility customizing your tester's sign-in experience, so it can better match your app's look and feel.

В следующем примере проверяется, вошел ли тестировщик уже в свою учетную запись тестировщика Firebase App Distribution , поэтому вы можете отображать интерфейс входа в систему только для тестировщиков, которые еще не вошли в систему. После того, как тестировщик войдет в систему, вы можете вызвать checkForUpdate() , чтобы проверить, имеет ли он доступ к новой сборке.

Быстрый

Note: This product is not available on macOS, Mac Catalyst, tvOS or watchOS targets.
// Sign in a tester without automatically checking for update
if (!AppDistribution.appDistribution().isTesterSignedIn) {
  AppDistribution.appDistribution().signInTester (completion: { error in
    // completion block for signInTester
     if (error != nil) {
       // handle failed sign in
      return
     }
    // handle successful sign in
  })
}

// Only check for update if tester is already signed in - do not prompt
if (AppDistribution.appDistribution().isTesterSignedIn) {
  AppDistribution.appDistribution().checkForUpdate(completion: { release, error in
      // completion block for check for update
  })
}

Objective-C

Note: This product is not available on macOS, Mac Catalyst, tvOS or watchOS targets.
// Sign in a tester without automatically checking for update
if(![[FIRAppDistribution appDistribution] isTesterSignedIn]) {
  [[FIRAppDistribution appDistribution]
    signInTesterWithCompletion:^(NSError *_Nullable error) {
      // completion block for signInTester
     if (error) {
       // handle failed sign in
       return;
     }
      // handle successful sign in
  }];
}

// only check for update if tester is already signed in - do not prompt
if([[FIRAppDistribution appDistribution] isTesterSignedIn]) {
  [[FIRAppDistribution appDistribution]
        checkForUpdateWithCompletion:^(FIRAppDistributionRelease *_Nullable release,
                                       NSError *_Nullable error) {
     // completion block for check for update
  }];
}

For information on additional methods, including signOutTester() , see the App Distribution reference documentation for Swift and Objective-C .

Шаг 4 : Создайте и протестируйте свою реализацию.

Finally, build your app and test your implementation by distributing the build to testers using the Firebase console.

Visit the App Distribution Troubleshooting guide for help with common issues, such as:

  • Тестировщик не получает внутриприложения уведомления
  • Tester being prompted to sign in to Google more than once