Interstitial ads are full-screen ads that cover the interface of an app until closed by the user. They're typically displayed at natural transition points in the flow of an app, such as between activities or during the pause between levels in a game. When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app. Case study .
В этом руководстве показано, как интегрировать межстраничную рекламу в iOS-приложение.
Предварительные требования
Прежде чем продолжить, настройте Google Mobile Ads SDK .
Всегда проводите тестирование с помощью тестовых объявлений.
При разработке и тестировании приложений обязательно используйте тестовые объявления, а не реальные, рабочие объявления. Несоблюдение этого правила может привести к блокировке вашего аккаунта.
Самый простой способ загрузить тестовые объявления — использовать наш специальный идентификатор тестового рекламного блока для межстраничной рекламы в iOS:
/21775744923/example/interstitial
Он специально настроен на возврат тестовых объявлений для каждого запроса, и вы можете свободно использовать его в своих приложениях во время кодирования, тестирования и отладки. Просто убедитесь, что вы заменили его на свой собственный идентификатор рекламного блока перед публикацией приложения.
Подробную информацию о тестовых объявлениях в Google Mobile Ads SDK см. в разделе «Включение тестовых объявлений» .
Выполнение
Основные шаги по интеграции межстраничной рекламы:
- Загрузить рекламу.
- Зарегистрируйтесь для участия в обратном звонке.
- Показать рекламу.
Загрузить рекламу
Загрузка рекламы осуществляется с помощью метода load(adUnitID:request) класса GAMInterstitialAd .
Быстрый
fileprivate func loadInterstitial() async {
do {
interstitial = try await AdManagerInterstitialAd.load(
with: "/21775744923/example/interstitial", request: AdManagerRequest())
interstitial?.fullScreenContentDelegate = self
} catch {
print("Failed to load interstitial ad with error: \(error.localizedDescription)")
}
}
SwiftUI
import GoogleMobileAds
class InterstitialViewModel: NSObject, FullScreenContentDelegate {
private var interstitialAd: InterstitialAd?
func loadAd() async {
do {
interstitialAd = try await InterstitialAd.load(
with: "ca-app-pub-3940256099942544/4411468910", request: Request())
interstitialAd?.fullScreenContentDelegate = self
} catch {
print("Failed to load interstitial ad with error: \(error.localizedDescription)")
}
}
Objective-C
[GAMInterstitialAd loadWithAdManagerAdUnitID:@"/21775744923/example/interstitial"
request:[GAMRequest request]
completionHandler:^(GAMInterstitialAd *ad, NSError *error) {
if (error) {
NSLog(@"Failed to load interstitial ad with error: %@",
[error localizedDescription]);
return;
}
self.interstitial = ad;
self.interstitial.fullScreenContentDelegate = self;
}];
Зарегистрируйтесь для участия в обратном звонке.
Для получения уведомлений о событиях презентации необходимо присвоить атрибут GADFullScreenContentDelegate свойству fullScreenContentDelegate возвращаемого объявления:
Быстрый
interstitial?.fullScreenContentDelegate = self
SwiftUI
interstitialAd?.fullScreenContentDelegate = self
Objective-C
self.interstitial.fullScreenContentDelegate = self;
Протокол GADFullScreenContentDelegate обрабатывает обратные вызовы в случае успешного или неудачного показа рекламы, а также при её закрытии. Следующий код демонстрирует реализацию протокола:
Быстрый
func adDidRecordImpression(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
}
func adDidRecordClick(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
}
func ad(_ ad: FullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
print("\(#function) called with error: \(error.localizedDescription)")
// Clear the interstitial ad.
interstitial = nil
}
func adWillPresentFullScreenContent(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
}
func adWillDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
}
func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
// Clear the interstitial ad.
interstitial = nil
}
SwiftUI
func adDidRecordImpression(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
}
func adDidRecordClick(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
}
func ad(
_ ad: FullScreenPresentingAd,
didFailToPresentFullScreenContentWithError error: Error
) {
print("\(#function) called")
}
func adWillPresentFullScreenContent(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
}
func adWillDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
}
func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
// Clear the interstitial ad.
interstitialAd = nil
}
Objective-C
- (void)adDidRecordImpression:(id<GADFullScreenPresentingAd>)ad {
NSLog(@"%s called", __PRETTY_FUNCTION__);
}
- (void)adDidRecordClick:(id<GADFullScreenPresentingAd>)ad {
NSLog(@"%s called", __PRETTY_FUNCTION__);
}
- (void)ad:(id<GADFullScreenPresentingAd>)ad
didFailToPresentFullScreenContentWithError:(NSError *)error {
NSLog(@"%s called with error: %@", __PRETTY_FUNCTION__, error.localizedDescription);
// Clear the interstitial ad.
self.interstitial = nil;
}
- (void)adWillPresentFullScreenContent:(id<GADFullScreenPresentingAd>)ad {
NSLog(@"%s called", __PRETTY_FUNCTION__);
}
- (void)adWillDismissFullScreenContent:(id<GADFullScreenPresentingAd>)ad {
NSLog(@"%s called", __PRETTY_FUNCTION__);
}
- (void)adDidDismissFullScreenContent:(id<GADFullScreenPresentingAd>)ad {
NSLog(@"%s called", __PRETTY_FUNCTION__);
// Clear the interstitial ad.
self.interstitial = nil;
}
Объект GAMInterstitialAd является одноразовым. Это означает, что после показа межстраничной рекламы её нельзя показать снова. Рекомендуется загружать следующую межстраничную рекламу в методе adDidDismissFullScreenContent: класса GADFullScreenContentDelegate , чтобы следующая межстраничная реклама начала загружаться сразу после закрытия предыдущей.
Показать объявление
Всплывающие рекламные ролики следует показывать во время естественных пауз в процессе работы приложения. Хорошим примером является переход между уровнями игры или после того, как пользователь выполнит какое-либо задание.
Быстрый
ad.present(from: self!)
SwiftUI
Отслеживайте события пользовательского интерфейса в представлении, чтобы определить, когда показывать рекламу.
var body: some View {
// ...
}
.onChange(of: countdownTimer.isComplete) { newValue in
showGameOverAlert = newValue
}
.alert(isPresented: $showGameOverAlert) {
Alert(
title: Text("Game Over"),
message: Text("You lasted \(countdownTimer.countdownTime) seconds"),
dismissButton: .cancel(
Text("OK"),
action: {
viewModel.showAd()
}))
Предъявите промежуточную рекламу, используя модель просмотра:
func showAd() {
guard let interstitialAd = interstitialAd else {
return print("Ad wasn't ready.")
}
interstitialAd.present(from: nil)
}
Objective-C
[self.interstitial presentFromRootViewController:self];
Передовые методы
- Подумайте, подходят ли для вашего приложения межстраничные объявления.
- Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.
- Не забудьте приостановить показ межстраничной рекламы.
- There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app. You can resume playing sounds in the
adDidDismissFullScreenContent:event handler, which will be invoked when the user has finished interacting with the ad. In addition, consider temporarily halting any intense computation tasks (such as a game loop) while the ad is being displayed. This will ensure that the user doesn't experience slow or unresponsive graphics or stuttered video. - Предусмотрите достаточное время для погрузки.
- Так же, как важно показывать межстраничную рекламу в подходящее время, важно также убедиться, что пользователю не приходится ждать ее загрузки. Предварительная загрузка рекламы перед ее показом гарантирует, что в вашем приложении будет полностью загружена межстраничная реклама, готовая к показу в нужный момент.
- Не заваливайте пользователя рекламой.
- Увеличение частоты показа межстраничной рекламы в вашем приложении может показаться отличным способом увеличить доход, но это также может ухудшить пользовательский опыт и снизить коэффициент кликабельности. Убедитесь, что пользователи не сталкиваются с настолько частыми прерываниями, что перестают получать удовольствие от использования вашего приложения.
- Не используйте функцию обратного вызова завершения загрузки для отображения промежуточного окна.
- Это может привести к ухудшению пользовательского опыта. Вместо этого предварительно загрузите рекламу перед тем, как её нужно будет показать. Затем проверьте метод
canPresentFromRootViewController:error:вGAMInterstitialAd, чтобы узнать, готова ли она к показу.
Примеры на GitHub
Просмотрите полные примеры межстраничных объявлений на предпочитаемом вами языке:
Следующие шаги
- Узнайте больше о таргетинге рекламы и правилах показа межстраничной рекламы .
- Узнайте больше о конфиденциальности пользователей .