Implementare gli annunci Picture in picture (beta)

Seleziona la piattaforma: Android iOS

Picture in picture

Gli annunci Picture in picture (PIP) vengono visualizzati in una finestra mobile che rimane in primo piano rispetto ai contenuti sullo schermo, come articoli, feed o gameplay. Questo formato consente agli utenti di interagire con la tua app mentre l'annuncio rimane visibile. Scegli questo formato per visualizzare annunci che non occupano l'intero schermo. Scopri di più sugli annunci picture in picture.

Questa guida spiega come richiedere e visualizzare gli annunci Picture in picture nella tua app utilizzando Google Mobile Ads SDK.

Prima di iniziare

Prima di continuare, completa queste operazioni:

Carica un annuncio

Per caricare un oggetto GADPictureInPictureAd, crea una richiesta di annuncio e chiama il metodo 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)")
  }
}

Sostituisci adUnitID con l'ID unità pubblicitaria.

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;
      }];
}

Sostituisci kAdUnitID con l'ID unità pubblicitaria.

Mostra l'annuncio

Per visualizzare l'annuncio Picture in picture sullo schermo, configura le opzioni Picture in picture e chiama il metodo show. L'esempio seguente imposta la posizione predefinita dell'annuncio e l'ambito della presentazione sullo schermo:

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];
}

Impostare la posizione

Per impostazione predefinita, Google Mobile Ads SDK mostra un annuncio picture in picture nell'angolo in basso a destra dello schermo quando viene visualizzato per la prima volta o nell'ultima posizione nota se è già stato mostrato. Per personalizzare la posizione in cui viene visualizzato l'annuncio, imposta la posizione nelle opzioni Picture in Picture. L'esempio seguente imposta la posizione sopra i contenuti nell'angolo in alto a sinistra dello schermo:

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;
}

Per tutte le posizioni disponibili, consulta GADPictureInPictureAdPosition.

Impostare l'ambito della presentazione

Per impostazione predefinita, Google Mobile Ads SDK associa un annuncio Picture in picture alla schermata host corrente. Google Mobile Ads SDK ignora l'annuncio quando la gerarchia di oggetti View dello schermo dell'app host non è più in memoria. Per mantenere l'annuncio visibile dopo la rimozione della schermata host dalla memoria, imposta l'ambito di presentazione sull'applicazione:

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;
}

Per saperne di più, consulta Mantenere l'annuncio visibile su più schermi.

Imposta il callback dell'evento annuncio

Per gestire gli eventi del ciclo di vita degli annunci Picture in picture, imposta il callback dell'evento sull'annuncio prima di visualizzarlo. Questo callback segnala eventi standard, come clic e impressioni. Questo callback segnala anche eventi specifici della modalità Picture in picture, ad esempio quando l'annuncio viene mostrato o nascosto:

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.");
}

Nascondere l'annuncio

Per rimuovere l'annuncio mobile dallo schermo, chiama il metodo hide. Questo metodo richiama il callback dell'evento di annuncio nascosto:

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];
}

Libera spazio dalle risorse pubblicitarie

Per evitare perdite di memoria, elimina il riferimento all'oggetto annuncio quando la tua app termina di utilizzare l'annuncio. Ad esempio, quando l'app non mostra più l'annuncio o non interagisce più con esso. Per gli annunci con ambito schermo, rilascia il riferimento quando la tua app rimuove lo schermo host dalla memoria. Per gli annunci con ambito app, mantieni il riferimento all'annuncio mentre l'utente naviga tra le schermate e rilascia il riferimento quando l'utente chiude l'annuncio:

Swift

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

Objective-C

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

Mantenere l'annuncio visibile su tutti gli schermi

Quando imposti l'ambito della presentazione sull'applicazione, l'annuncio in modalità Picture in picture rimane visibile anche quando l'app rimuove la schermata di hosting dalla memoria. Per interagire con l'annuncio o chiuderlo quando l'utente esce dalla schermata host, la tua app deve mantenere l'accesso all'annuncio Picture in picture. Ti consigliamo di inserire l'annuncio in un singleton a livello di app o in un gestore di stato condiviso anziché in una variabile di istanza di una singola schermata.