シミュレータのエキスパートになる – WWDC2020

Session概要

シミュレータはMac上でiOS, iPadOS, tvOS, watchOSのアプリを別のデバイスは必要なく、直接起動させる。
アプリの最新ツールや特徴を紹介し、シミュレータスキルを磨く方法について。
ポインタやトラックパッドサポートのテスト方法、Simulator Preferencesの調整方法、開発環境におけるPush通知のシミュレーションに役立つsimctlのようなコマンドラインツールの使用方法について https://developer.apple.com/videos/play/wwdc2020/10647/

シミュレータについて

  • Xcodeに内蔵されており、物理デバイスなしでアプリの実行やテストを行う際に自動で起動する
  • トップにツールバーがあり、よく利用されるプラットフォームの機能がある
    • スクリーンショット
      • スクリーンショットのサムネイルをControlキーを押しながらクリックすると別のアプリケーションで開くなどの操作が可能
      • デフォルトでは、デスクトップフォルダに保存される
    • ポインター(for iPad)
      • iPadOSはマウスポインターの相互作用をサポートする
        • ユーザがiPadにマウスやトラックパッドを接続した時にポインターとジェスチャーの完全なサポートが得られる。すなわち、マウスやトラックパッドがシミュレータ上で動くようになる
        • これにより、指でのピンチイン/アウト、キーボードショートカットなどのテストが容易にできるようになった
        • ポインターをMacに戻すには Escapeキーを押す
      • ポインターやキーボードのキャプチャはMacでシミュレータ以外を操作すると自動的に解除され、シミュレータに戻るとキャプチャは再開する
  • ファイルをシミュレータにドラッグしてイメージをフォトライブラリーに追加することや、Push通知をトリガーする、証明書を追加するなどの特定イベントを発生させることも可能
  • Xcode 12ではシミュレータをフルスクリーンモードで表示可能で、別アプリケーションとタイル配置可能

シミュレータの環境設定

  • キャプチャを止めるショートカットの設定(defaultはEscキー)
  • 起動中のシミュレータのライフタイム設定
    • シミュレータを起動する際に使用するシミュレータの種類の設定など
  • ビジュアルインジケーター設定
    • シミュレータでのスクリーンショットにおいて、maskを行うなど

メニューバーの「機能(Feature)」タブ

  • シミュレータのプラットフォームによって利用可能な機能が異なる
  • Toggle Appearance
    • iOSのLightモードとDarkモードを切り替える

新しいシミュレータの追加

  • シミュレータのメニューバーから「File」タブ開き、New Simulatorをクリック
  • 名前、デバイスタイプとOS versionを設定して追加する

サイズについて

  • デフォルトは物理的なサイズと同等
    • ただし、pixel数からinchを算出するため、起動するmacの解像度によってサイズは異なる
  • シミュレータの角をドラッグすることや、command + 4などのショートカットキーで調整可能

Point Accurateモード

  • ウィンドウのサイズを一定の大きさにすることで、スケールファクターが異なるデバイス上でもコンテンツは同じサイズで表示される
  • すなわち、シミュレータデバイスの画素密度に関係なく全てのシミュレータのポイントは画面上で同じになる
    • そのため、シミュレータデバイスの解像度と表示するmacの解像度によってダウンスケールが発生する(サイズは同じになっているため)

Pixel Accurate表示モード

  • シミュレートするデバイスの各画素はMacのディスプレイ上の画素に直接マッピングされる
    • Macのディスプレイの画素密度がシミュレートするデバイスより低い場合、シミュレータは画面上ではより大きく表示される

CLIによるシミュレータへのアクセス

  • simctl(Simulator control)ツールを使用することで、コマンドラインからシミュレータを制御可能
  • simctlの詳細はterminalでxcrun simctl コマンド(オプションなし)を実行すると確認可能
❯ xcrun simctl
usage: simctl [--set <path>] [--profiles <path>] <subcommand> ...
       simctl help [subcommand]
Command line utility to control the Simulator

For subcommands that require a <device> argument, you may specify a device UDID
or the special "booted" string which will cause simctl to pick a booted device.
If multiple devices are booted when the "booted" device is selected, simctl
will choose one of them.

Subcommands:
    create              Create a new device.
    clone               Clone an existing device.
    upgrade             Upgrade a device to a newer runtime.
    delete              Delete spcified devices, unavailable devices, or all devices.
    pair                Create a new watch and phone pair.
    unpair              Unpair a watch and phone pair.
    pair_activate       Set a given pair as active.
    erase               Erase a device's contents and settings.
    boot                Boot a device.
    shutdown            Shutdown a device.
    rename              Rename a device.
    getenv              Print an environment variable from a running device.
    openurl             Open a URL in a device.
    addmedia            Add photos, live photos, videos, or contacts to the library of a device.
    install             Install an app on a device.
    uninstall           Uninstall an app from a device.
    get_app_container   Print the path of the installed app's container
    install_app_data    Install an xcappdata package to a device, replacing the current contents of the container.
    launch              Launch an application by identifier on a device.
    terminate           Terminate an application by identifier on a device.
    spawn               Spawn a process by executing a given executable on a device.
    list                List available devices, device types, runtimes, or device pairs.
    icloud_sync         Trigger iCloud sync on a device.
    pbsync              Sync the pasteboard content from one pasteboard to another.
    pbcopy              Copy standard input onto the device pasteboard.
    pbpaste             Print the contents of the device's pasteboard to standard output.
    help                Prints the usage for a given subcommand.
    io                  Set up a device IO operation.
    diagnose            Collect diagnostic information and logs.
    logverbose          enable or disable verbose logging for a device
    status_bar          Set or clear status bar overrides
    ui                  Get or Set UI options
    push                Send a simulated push notification
    privacy             Grant, revoke, or reset privacy and permissions
    keychain            Manipulate a device's keychain

プライバシー

  • アプリを利用する際に、機能によってユーザの許可を求めるプロンプトを表示する必要があり、許可時と保留の両方がどのように機能するのかを確認する必要がある
  • simctlを使用して、保護されたリソースへのアプリのアクセス権をコマンドラインから付与したり取り消したりすることが可能
  • simctlの対象シミュレータは起動中のシミュレータで、複数起動している場合はシミュレータの名前かUDIDを指定する
// 権限の付与
xcrun simctl privacy booted grant calender com.example.MyApp

// 権限の削除
// 下記では、アプリをcalenderに指定したが、all を指定することで全てのアプリに設定も可能
xcrun simctl privacy booted revoke calender com.example.MyApp

// 権限のリセット
xcrun simctl privacy reset all

push通知

  • 下記はタイトル、本文を通知する例
{
  "Simulator Target Bundle": "com.example.MyApp", // このキーは、通知を受信するアプリのbundle idを指定する
  "aps": {
       "alert": {
           "title": "Push Notification",
           "subtitle": "New fruit smoothies are available",
           "body": "We know you'll love these delicious concoctions 🥰"
       }
   }
}
xcrun simctl push booted com.example.MyApp payload.json

// bundle IDを省略可能
xcrun simctl push booted payload.json

videoの録画

  • QuickTimeなどを使用した画面録画は不要で、シミュレータで可能
  • simctlを使用すると、Simulator.appの実行なしで可能
    • control + cで録画を終了する
    • simctlでの録画はGPUを使用してビデオのエンコードを加速するためシステムリソースは多く使用しない
// 動作中のデバイスから画面のビデオをキャプチャしてvideo.mp4に保存
// 既にファイルが存在して上書きする場合は --force オプションを追加する
xcrun simctl io booted recordVideo video.mp4

// codecの指定、maskの削除
crun simctl io booted recordVideo --codec h264 --mask ignored video.mp4

// 内蔵 or 外部ディスプレイのどちらでビデオ映像をキャプチャするかを選択可能
// 例えば、写真アプリでの表示を外部ディスプレイに映すなど
xcrun simctl io booted recordVideo --display external external.mp4

ステータスバー(Status bar)

  • simctlでステータスバーの状態を編集可能
    • App Store用のスクリーンショットを撮る際に有用
  • バッテリーの状態変更によるアプリの動作確認などは使えそう
// ステータスバーの時間、ネットワーク環境を変更
xcrun simctl status_bar booted override --time 12:01 --cellularBars 1 --dataNetwork 3g --wifiMode failed

// 編集したステータスバーをclearする
xcrun simctl status_bar booted clear
❯ xcrun simctl status_bar
Set or clear status bar overrides
Usage: simctl status_bar <device> [list | clear | override <override arguments>]

Supported Operations:
    list
    List existing overrides.

    clear
    Clear all existing status bar overrides.

    override <override arguments>
    Set status bar override values, according to these flags.
    You may specify any combination of these flags (at least one is required):

    --time <string>
         Set the date or time to a fixed value.
         If the string is a valid ISO date string it will also set the date on relevant devices.
    --dataNetwork <dataNetworkType>
         If specified must be one of 'wifi', '3g', '4g', 'lte', 'lte-a', or 'lte+'.
    --wifiMode <mode>
         If specified must be one of 'searching', 'failed', or 'active'.
    --wifiBars <int>
         If specified must be 0-3.
    --cellularMode <mode>
         If specified must be one of 'notSupported', 'searching', 'failed', or 'active'.
    --cellularBars <int>
         If specified must be 0-4.
    --operatorName <string>
         Set the cellular operator/carrier name. Use '' for the empty string.
    --batteryState <state>
         If specified must be one of 'charging', 'charged', or 'discharging'.
    --batteryLevel <int>
         If specified must be 0-100

キーチェーン(Keychain)

  • simctlにより、デバイスの信頼されたルート証明書ストアにCA証明書を追加することができる
  • simctl以外にも、証明書を「シミュレータ」ウィンドウにドラッグして追加することもできる
  • 証明書を信頼するには、
    • 設定アプリ → 一般 → 情報 → 証明書信頼設定 → 対象の証明書をスイッチでアクティブにする
  • その他、保存されたパスワードを削除したりすることも可能
xcrun simctl keychain booted add-root-cert myCA.pem
最新情報をチェックしよう!