6
8

More than 3 years have passed since last update.

SwiftUI製アプリにFirebase Crashlyticsを導入する

Posted at

概要

初投稿です...!
SwiftUIの勉強もかねて個人アプリを作成したので、そのときに導入したCrashlyticsの導入方法について記載します。
すでにcocoaPodsやFirebaseの機能の一部を使っていたので、多少端折っています。
プロジェクトの作成や初期設定方法については公式ドキュメントを参照してください。
https://firebase.google.com/docs/crashlytics/get-started?platform=ios

Firebase Crashlyticsとは

クラッシュレポートを収集して解析するためのサービスです。
他にもSmartbeatなど、複数のクラッシュレポートサービスが存在します。

導入方法

1.Crashlyticsのインストール

まずはPodfileを更新します。

Podfile

pod 'Firebase/Crashlytics'
pod 'Firebase/Analytics'

Podfileを更新後、下記を実行してライブラリを使えるようにします。

$ pod install

2. XcodeのBuild PhasesからRun Scriptセクションを追加する

下記画像のように左の+ボタンからRun Scriptを生成します。
Run Script

3. Run Scriptに必要な設定を記述する

Shellフィールドの下に
以下のコードを記述します。

"${PODS_ROOT}/FirebaseCrashlytics/run"

次にInput Filesにある+ボタンを2回押して、それぞれの行に以下のコードを記載します。

${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${TARGET_NAME}
$(SRCROOT)/$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)

画像のようになっていればOKです。
Run Script Content

4. XcodeのBuild Settingsの設定を変更する

XcodeのBuild Settingsのタブを開き、Debug Information FormatのDEBUGの設定を「DWARF」から「DWARF with dSYM File」に変更します。
Debug Information Format

5. AppDelegate.swiftを用意して、Firebaseの共有インスタンスを構成する

自分はAppDelegateを用意して初期化しましたが、Main Viewのinit部分で行っても問題ないと思います。

AppDelegate.swift
import Firebase
import UIKit

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        FirebaseApp.configure()
        return true
    }
}

AppDelegateを参照できるようにする

???.swift
@main
struct ???: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

6. 任意のViewにクラッシュさせるボタンを配置する

以下のようなボタンを設置してクラッシュさせてください

ContentView.swift
struct ContentView: View {
    var body: some View {
        Button(action: {
            fatalError()
        }, label: {
            Text("クラッシュさせる")
        })
    }
}

これでFirebaseのCrashlyticsのダッシュボードに該当のクラッシュイベントが表示されると思います。

Crashlytics dash board

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8