fastlane でスクリーンショット撮影するまでのセットアップ

fastlane snapshot を試してみたのでメモ。

資料

fastlane snapshot 導入のメリット

導入のコストはそんなに大きくなく、得られるメリットの方が大きいとおもう。

  • UITests の実行状態をスクリーンショットで記録できる。
    • UITests はパスした上での問題(更新により前回とデザインが変わってしまった、など)を確認できる。
  • AppStore 提出用のスクリーンショットを自動で撮影できる。

セットアップ

Homebrew 経由でインストール(gem でも良い)

$ brew install fastlane

インストール確認

$ which fastlane

インストールされている場合はパスが表示されるハズ。

プロジェクトのルートで fastlane を初期化

$ fastlane snapshot init

fastlane フォルダができる。その中に以下のファイルができる。

  • Snapfile (設定ファイル)
  • SnapshotHelper.swift
    • UITests のターゲットに追加する。

UITests に撮影コードを追加

UnitTests に以下の記載を追加する。

class UITests: XCTestCase {
    func testExample() throws {
            let app = XCUIApplication()
            setupSnapshot(app)  // ⭐️ fastlane snapshot をセットアップ
            app.launch()
            snapshot("launch")  // ⭐️ ファイル名を指定して撮影
    }
}

Snapfile 編集

Snapfile はスクリーンショット撮影の設定ファイル。ここに必要な設定を書く。

とりあえず、以下のようにして iPhone 11 で英語の状態で撮影されるようにする。

# Uncomment the lines below you want to change by removing the # in the beginning

# A list of devices you want to take the screenshots from
devices([
#   "iPhone 8",
#   "iPhone 8 Plus",
#   "iPhone SE",
#   "iPhone X",
#   "iPad Pro (12.9-inch)",
#   "iPad Pro (9.7-inch)",
#   "Apple TV 1080p"
    "iPhone 11", // ⭐️ iPhone 11 シミュレーターで撮影
])

languages([
    "en-US",  // ⭐️ 言語は en-US だけ
#   "de-DE",
#   "it-IT",
#   ["pt", "pt_BR"] # Portuguese with Brazilian locale
])

# The name of the scheme which contains the UI Tests
scheme("⭐️UITests を含んでいるスキームの名前")

# Where should the resulting screenshots be stored?
output_directory("./screenshots")

# remove the '#' to clear all previously generated screenshots before creating new ones
clear_previous_screenshots(true)

# Remove the '#' to set the status bar to 9:41 AM, and show full battery and reception.
override_status_bar(true)

# Arguments to pass to the app on launch. See https://docs.fastlane.tools/actions/snapshot/#launch-arguments
# launch_arguments(["-favColor red"])

# For more information about all available options run
# fastlane action snapshot

実行

プロジェクトのルート(fastlane フォルダの中ではない)で以下を実行。

$ fastlane snapshot run

プロジェクトのビルドが始まり、成功すると screenshotフォルダができて、ファイルが作られる。

fastlane のコマンドではなく、Xcode から直接ユニットテストを実行するとスクリーンショットは作成されないことに注意。

スクリーンショット撮影のコンディションを Snapfile で指定したい

たとえば「広告が非表示の状態」で撮影したいとする。

この場合の対応方法のひとつとして、まず Snapfile でアプリの起動引数が指定できるので、以下のように設定する。

# Arguments to pass to the app on launch. See https://docs.fastlane.tools/actions/snapshot/#launch-arguments
# launch_arguments(["-favColor red"])
launch_arguments(["-hiddenAd"])  // ⭐️ 起動引数設定

そして設定された起動引数でアプリ内で動作を変更すると、広告が消えた状態で撮影できる。

// 起動引数を確認
if ProcessInfo.processInfo.arguments.contains("-hiddenAd") {
    // 広告を非表示にする
}

// CommondLine クラスを使っても起動引数は確認できる
if CommandLine.arguments.contains("-hiddenAd") {
    // 広告を非表示にする
}