使用 Firebase Crashlytics 记录广告响应 ID

Firebase Crashlytics 是一款轻量级的实时崩溃报告解决方案,可让您轻松管理应用中的稳定性问题。Crashlytics 会对崩溃进行智能分组并突出显示导致这些崩溃的环境因素,从而为您节省问题排查的时间。

本指南介绍了如何将 Crashlytics 集成到您的 Xcode 项目中,以便您记录广告响应 ID。之后,在排查应用中的崩溃问题时,您可以查找广告响应 ID,并使用 AdMob 中的广告审核中心查找和屏蔽广告。

第 1 步:将 Firebase 添加到 iOS 应用

  1. 如果您想尝试在一个干净的应用中使用 Firebase 进行日志记录,可以在 GitHub 上下载或克隆适用于 iOS 代码库的 Google 移动广告 SDK 示例。本指南具体采用的是 横幅广告示例

    如果您已有应用,则应该能够使用应用的软件包 ID 继续执行其他步骤。您也可以对代码库中的其他示例采取同样的步骤,只需稍作调整即可。

  2. 如需使用 Firebase Crashlytics,您必须创建一个 Firebase 项目,并将您的应用添加到其中。如果您还没有 Firebase 项目,请创建一个。请务必向其中注册您的应用

    1. 在 Firebase 控制台的 Crashlytics 页面中,点击设置 Crashlytics

    2. 在随即显示的屏幕中,依次点击否 > 设置新的 Firebase 应用

  3. 在 Podfile 中,为 Google Analytics(分析)和 Firebase Crashlytics 添加 Pod。

    source 'https://github.com/CocoaPods/Specs.git'
    
    platform :ios, '8.0'
    
    target 'BannerExample' do
      use_frameworks!
      pod 'Google-Mobile-Ads-SDK'
      pod 'Firebase/Crashlytics'
      pod 'Firebase/Analytics'
    end
    
  4. 在终端或命令提示符中,安装并更新您的 Pod:

    pod install --repo-update
    
  5. 打开 Xcode 的 BannerExample.xcworkspace 文件以加载项目。

第 2 步:为您的应用配置 Firebase

Swift

在您的 AppDelegate.swift 中,添加以下几行代码:

import UIKit

// Import the Firebase library
import FirebaseCore

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(_ application: UIApplication,
      didFinishLaunchingWithOptions launchOptions:
          [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Configure an instance of Firebase
    FirebaseApp.configure()
    return true
  }
}

Objective-C

在您的 AppDelegate.m 中,添加以下几行代码:

@import AppDelegate.h;

// Import the Firebase library
@import FirebaseCore;

@interface AppDelegate ()

@end

@implementation AppDelegate

‐ (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    // Initialize Firebase
    [FIRApp configure];
    return YES;
}

在 Xcode 中,打开 Build Settings,然后点击 Build Phases(构建阶段)标签页。添加 Fabric 运行脚本:

清理 build 文件夹,然后构建并运行您的应用。现在,您可以登录 Firebase Web 控制台,并访问 Crashlytics 信息中心。

(可选):测试设置

通过添加崩溃按钮,您可以强制造成崩溃。也就是说,每次按下按钮时,应用便会崩溃。此测试设置将触发第 3 步中的代码,以将自定义日志发送到 Firebase Crashlytic 信息中心。

Swift

在您的 ViewController.swift 中,将以下几行代码添加到 viewDidLoad() 函数中:

    override func viewDidLoad() {
        super.viewDidLoad()
        print("Google Mobile Ads SDK version: \(GADRequest.sdkVersion())")
        bannerView.delegate = self
        bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
        bannerView.rootViewController = self
        bannerView.load(GADRequest())
        let button = UIButton(type: .roundedRect)
        button.frame = CGRect(x: 20, y: 50, width: 100, height: 30)
        button.setTitle("Crash", for: [])
        button.addTarget(self, action: #selector(self.crashButtonTapped(_:)),
            for: .touchUpInside)
        view.addSubview(button)
    }

然后,将此 @IBAction 添加到类声明的底部:

    @IBAction func crashButtonTapped(_ sender: AnyObject) {
        fatalError("Test Crash Happened")
    }

Objective-C

ViewController.m 中,将以下几行代码添加到 viewDidLoad 方法中:

‐ (void)viewDidLoad {
    [super viewDidLoad];

    /// ...

    UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(20, 50, 100, 30);
    [button setTitle:@"Crash" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(crashButtonTapped:)
        forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

然后,将此 IBAction 添加到类声明的底部:

‐ (IBAction)crashButtonTapped:(id)sender {
    assert(NO);
}

在 Xcode 工具栏中,按 Stop 按钮,然后通过模拟器重新启动应用。加载应用后,您可以点击 Crash 按钮。返回 Xcode,然后点击崩溃日志的 Play(播放)按钮,以便将崩溃日志上传到 Crashlytics。

第 3 步:记录广告响应 ID

如果您加载多个广告并在不同时间展示,最好使用单独的键记录每个广告响应 ID。例如,本指南使用的示例只包含一个横幅广告。因此,我们会在以下代码段中将广告响应 ID 记录为 banner_ad_response_id 键。

您还可以在 Firebase Crashlytics 中针对不同的广告类型和广告事件创建多个自定义键值对。参阅广告请求生命周期通知

如需详细了解自定义日志记录,请访问自定义 Firebase Crashlytics 崩溃报告

Swift

将以下代码添加到 ViewController.swift 中。从本质上讲,它使用 adViewDidReceiveAd 回调函数中的 Crashlytics.setCustomValue() 函数。

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADBannerViewDelegate {

    /// The banner view.
    @IBOutlet weak var bannerView: GADBannerView!

    override func viewDidLoad() {
       super.viewDidLoad()
       ...
       bannerView.delegate = self
       ...
    }

    /// Tells the delegate an ad request loaded an ad.
    func adViewDidReceiveAd(_ bannerView: GADBannerView) {
        if let responseInfo = bannerView.responseInfo,
                responseId = responseInfo.responseId {
            print("adViewDidReceiveAd from network:
                \(responseInfo.adNetworkClassName), response Id='\(responseId)'")
            Crashlytics.sharedInstance().setCustomValue(responseId,
                forKey: "banner_ad_response_id")
        }
    }
}

Objective-C

将以下代码添加到 ViewController.m 中。从本质上讲,它使用的是 adViewDidReceiveAd 函数中的 [FIRCrashlytics crashlytics] setCustomValue 函数。

@import GoogleMobileAds;
@interface ViewController ()

@property(nonatomic, strong) GADBannerView *bannerView;

@end

@implementation ViewController

‐ (void)viewDidLoad {
  [super viewDidLoad];

  // In this case, we instantiate the banner with desired ad size.
  self.bannerView = [[GADBannerView alloc]
      initWithAdSize:GADAdSizeBanner];

  [self addBannerViewToView:self.bannerView];
}

‐ (void)addBannerViewToView:(UIView *)bannerView {
  bannerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:bannerView];
  [self.view addConstraints:@[
    [NSLayoutConstraint constraintWithItem:bannerView
                               attribute:NSLayoutAttributeBottom
                               relatedBy:NSLayoutRelationEqual
                                  toItem:self.bottomLayoutGuide
                               attribute:NSLayoutAttributeTop
                              multiplier:1
                                constant:0],
    [NSLayoutConstraint constraintWithItem:bannerView
                                 attribute:NSLayoutAttributeCenterX
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:self.view
                                kattribute:NSLayoutAttributeCenterX
                                multiplier:1
                                  constant:0]
                             ]];
}

- (void)adViewDidReceiveAd:(GADBannerView *)bannerView {
  NSString *adResponseId = bannerView.responseInfo.responseId;
  if (adResponseId) {
    NSLog(@"adViewDidReceiveAd from network: %@ with response Id: %@",
        bannerView.responseInfo.adNetworkClassName, adResponseId);
    [[FIRCrashlytics crashlytics] setCustomValue:adResponseId
                                          forKey:@"banner_ad_response_id"];
  }
}

@end

恭喜!现在,您可以在 Crashlytics 信息中心内崩溃会话的键部分看到最新 adResponseId 了。请注意,某些键最多可能需要 1 小时才会显示在信息中心内。