Implémenter les annonces Picture-in-picture (bêta)

Sélectionnez une plate-forme : Android iOS

Picture-in-picture

Les annonces picture-in-picture (PIP) s'affichent dans une fenêtre flottante qui reste au-dessus du contenu à l'écran, comme des articles, des flux ou des séquences de jeu. Ce format permet aux utilisateurs d'interagir avec votre application pendant que l'annonce reste visible. Choisissez ce format pour diffuser des annonces qui n'occupent pas tout l'écran. En savoir plus sur les annonces picture-in-picture

Ce guide explique comment demander et afficher des annonces au format Picture-in-picture dans votre application à l'aide de Google Mobile Ads SDK.

Avant de commencer

Avant de continuer, procédez comme suit :

Charger une annonce

Pour charger un objet GADPictureInPictureAd, créez une demande d'annonce et appelez la méthode load :

Swift

private func loadPictureInPictureAd() async {
  do {
    // Capture the PictureInPictureAd reference for later use.
    pipAd = try await PictureInPictureAd.load(
      with: adUnitID, request: Request())
    // Set the delegate to be notified of ad events.
    pipAd?.delegate = self
  } catch {
    print(
      "Picture-in-Picture ad failed to load: \(error.localizedDescription)")
  }
}

Remplacez adUnitID par l'ID de votre bloc d'annonces.

Objective-C

- (void)loadPictureInPictureAd {
  GADRequest *request = [GADRequest request];

  [GADPictureInPictureAd
       loadWithAdUnitID:kAdUnitID
                request:request
      completionHandler:^(GADPictureInPictureAd *_Nullable ad, NSError *_Nullable error) {
        if (error) {
          NSLog(@"Picture-in-Picture ad failed to load: %@", error);
          return;
        }
        // Capture the PictureInPictureAd reference for later use.
        self.pipAd = ad;
        // Set the delegate to be notified of ad events.
        self.pipAd.delegate = self;
      }];
}

Remplacez kAdUnitID par l'ID de votre bloc d'annonces.

Diffuser l'annonce

Pour afficher l'annonce Picture-in-picture à l'écran, configurez vos options Picture-in-picture et appelez la méthode show. L'exemple suivant définit la position par défaut de l'annonce et le champ d'application de la présentation sur l'écran :

Swift

private func showPictureInPictureAd() {
  // Use the loaded PictureInPictureAd instance.
  guard let pipAd else {
    print("No ad to show.")
    return
  }
  let options = PictureInPictureAdOptions()
  // Uses the Google Mobile Ads SDK's default screen position.
  options.position = .default
  // Binds the ad lifecycle to the host screen.
  options.presentationScope = .screen

  pipAd.show(with: options)
}

Objective-C

- (void)showPictureInPictureAd {
  // Use the loaded PictureInPictureAd instance.
  if (!self.pipAd) {
    NSLog(@"No ad to show.");
    return;
  }
  GADPictureInPictureAdOptions *options =
      [[GADPictureInPictureAdOptions alloc] init];
  // Uses the Google Mobile Ads SDK's default screen position.
  options.position = GADPictureInPictureAdPositionDefault;
  // Binds the ad lifecycle to the host screen.
  options.presentationScope = GADPictureInPictureAdPresentationScopeScreen;

  [self.pipAd showWithOptions:options];
}

Définir la position

Par défaut, Google Mobile Ads SDK affiche une annonce picture-in-picture en bas à droite de l'écran lors de sa première diffusion, ou à la dernière position connue si elle a déjà été diffusée. Pour personnaliser l'emplacement de l'annonce, définissez la position dans vos options d'image dans l'image. L'exemple suivant définit la position au-dessus du contenu, dans l'angle supérieur gauche de l'écran :

Swift

private func createTopLeftPositionOptions() -> PictureInPictureAdOptions {
  let options = PictureInPictureAdOptions()
  // Sets the ad position to the top-left corner of the screen.
  options.position = .topLeft
  return options
}

Objective-C

- (GADPictureInPictureAdOptions *)createTopLeftPositionOptions {
  GADPictureInPictureAdOptions *options =
      [[GADPictureInPictureAdOptions alloc] init];
  // Sets the ad position to the top-left corner of the screen.
  options.position = GADPictureInPictureAdPositionTopLeft;
  return options;
}

Pour connaître tous les postes disponibles, consultez GADPictureInPictureAdPosition.

Définir le champ d'application de la présentation

Par défaut, Google Mobile Ads SDK associe une annonce Picture-in-picture à l'écran hôte actuel. Google Mobile Ads SDK ferme l'annonce lorsque la hiérarchie des vues de l'écran hôte n'est plus en mémoire. Pour que l'annonce reste visible après la suppression de l'écran hôte de la mémoire, définissez le champ d'application de la présentation sur l'application :

Swift

private func createApplicationScopedOptions() -> PictureInPictureAdOptions {
  let options = PictureInPictureAdOptions()
  // Keeps the ad visible beyond the host screen's lifecycle.
  options.presentationScope = .application
  return options
}

Objective-C

- (GADPictureInPictureAdOptions *)createApplicationScopedOptions {
  GADPictureInPictureAdOptions *options =
      [[GADPictureInPictureAdOptions alloc] init];
  // Keeps the ad visible beyond the host screen's lifecycle.
  options.presentationScope = GADPictureInPictureAdPresentationScopeApplication;
  return options;
}

Pour en savoir plus, consultez Conserver la visibilité de l'annonce sur tous les écrans.

Définir le rappel d'événement d'annonce

Pour gérer les événements de cycle de vie des annonces Picture-in-picture, définissez le rappel d'événement sur votre annonce avant de l'afficher. Ce rappel signale les événements standards, tels que les clics et les impressions. Ce rappel signale également les événements spécifiques au mode Picture-in-picture, par exemple lorsque l'annonce est affichée ou masquée :

Swift

func pictureInPictureAdDidShow(_ pictureInPictureAd: PictureInPictureAd) {
  print("Picture-in-Picture ad shown.")
}

func pictureInPictureAdDidHide(_ pictureInPictureAd: PictureInPictureAd) {
  print("Picture-in-Picture ad hidden.")
}

func pictureInPictureAdDidFailToShow(
  _ pictureInPictureAd: PictureInPictureAd, error: Error
) {
  print("Picture-in-Picture ad failed to show: \(error.localizedDescription)")
}

func pictureInPictureAdDidRecordImpression(
  _ pictureInPictureAd: PictureInPictureAd
) {
  print("Picture-in-Picture ad recorded an impression.")
}

func pictureInPictureAdDidRecordClick(
  _ pictureInPictureAd: PictureInPictureAd
) {
  print("Picture-in-Picture ad recorded a click.")
}

func pictureInPictureAdWillPresentScreen(
  _ pictureInPictureAd: PictureInPictureAd
) {
  print("Picture-in-Picture ad will present screen.")
}

func pictureInPictureAdWillDismissScreen(
  _ pictureInPictureAd: PictureInPictureAd
) {
  print("Picture-in-Picture ad will dismiss screen.")
}

func pictureInPictureAdDidDismissScreen(
  _ pictureInPictureAd: PictureInPictureAd
) {
  print("Picture-in-Picture ad dismissed screen.")
}

Objective-C

- (void)pictureInPictureAdDidShow:(GADPictureInPictureAd *)pictureInPictureAd {
  NSLog(@"Picture-in-Picture ad shown.");
}

- (void)pictureInPictureAdDidHide:(GADPictureInPictureAd *)pictureInPictureAd {
  NSLog(@"Picture-in-Picture ad hidden.");
}

- (void)pictureInPictureAdDidFailToShow:(GADPictureInPictureAd *)pictureInPictureAd
                              withError:(NSError *)error {
  NSLog(@"Picture-in-Picture ad failed to show: %@", error);
}

- (void)pictureInPictureAdDidRecordImpression:(GADPictureInPictureAd *)pictureInPictureAd {
  NSLog(@"Picture-in-Picture ad recorded an impression.");
}

- (void)pictureInPictureAdDidRecordClick:(GADPictureInPictureAd *)pictureInPictureAd {
  NSLog(@"Picture-in-Picture ad recorded a click.");
}

- (void)pictureInPictureAdWillPresentScreen:(GADPictureInPictureAd *)pictureInPictureAd {
  NSLog(@"Picture-in-Picture ad will present screen.");
}

- (void)pictureInPictureAdWillDismissScreen:(GADPictureInPictureAd *)pictureInPictureAd {
  NSLog(@"Picture-in-Picture ad will dismiss screen.");
}

- (void)pictureInPictureAdDidDismissScreen:(GADPictureInPictureAd *)pictureInPictureAd {
  NSLog(@"Picture-in-Picture ad dismissed screen.");
}

Masquer l'annonce

Pour supprimer l'annonce flottante de l'écran, appelez la méthode hide. Cette méthode appelle le rappel d'événement d'annonce masquée :

Swift

private func hidePictureInPictureAd() {
  // Use the loaded PictureInPictureAd instance.
  guard let pipAd else {
    print("No ad to hide.")
    return
  }
  pipAd.hide()
}

Objective-C

- (void)hidePictureInPictureAd {
  // Use the loaded PictureInPictureAd instance.
  if (!self.pipAd) {
    NSLog(@"No ad to hide.");
    return;
  }
  [self.pipAd hide];
}

Nettoyer les composants d'annonce

Pour éviter les fuites de mémoire, supprimez votre référence à l'objet publicitaire lorsque votre application a fini d'utiliser l'annonce. Par exemple, lorsque votre application n'affiche plus l'annonce ou n'interagit plus avec elle. Pour les annonces à portée d'écran, supprimez la référence lorsque votre application supprime l'écran hôte de la mémoire. Pour les annonces limitées à l'application, conservez la référence de l'annonce pendant que l'utilisateur navigue entre les écrans, et supprimez-la lorsqu'il ferme l'annonce :

Swift

private func cleanUpPictureInPictureAd() {
  pipAd?.hide()
  pipAd = nil
}

Objective-C

- (void)cleanUpPictureInPictureAd {
  [self.pipAd hide];
  self.pipAd = nil;
}

Maintenir l'annonce visible sur tous les écrans

Lorsque vous définissez le champ d'application de la présentation sur l'application, l'annonce au format picture-in-picture reste visible même lorsque votre application supprime l'écran hôte de la mémoire. Pour interagir avec l'annonce ou la fermer lorsque l'utilisateur quitte l'écran hôte, votre application doit conserver l'accès à l'annonce au format Picture-in-picture. Nous vous recommandons de conserver l'annonce dans un gestionnaire d'état partagé ou singleton au niveau de l'application plutôt que dans la variable d'instance d'un seul écran.