【Xcode】Preview Crashed で 表示されない 📲

Xcode の Preview がクラッシュしっぱなし。

【Xcode】Preview Crashed で 表示されない

ストレージまわりの話ではないかと思いながらしらべる。


xcrun simctl -—set previews delete all

👉 Preview keeps crashing | Apple Developer Forums hatena-bookmark
👉 SwiftUIのプレビューが動かなくなった時の対処方法 #SwiftUI - Qiita hatena-bookmark

 

📲 ログから原因を見つける

まずは、見てみますか。


#!/bin/bash

cd ~/Library/Logs/DiagnosticReports
file=$(ls XCPreview* | head -1)
open $file

何か起こったらログ確認大事。

 

📲 対応方法

いろいろありそうです。

このシミュレータですが、通常のシミュレータとは別でXcodeが持っています。しかしストレージ管理のデベロッパ欄には表示されない上に自動で削除されません。私の環境ではiOS14.1のシミュレータなども残っていました。

👉 【SwiftUI】PreviewのSimulator残留 | thwork hatena-bookmark


cd ~/Library/Developer/Xcode/UserData/Previews/Simulator\ Devices/
find . -name com.apple.suggestions.plist -exec plutil -replace SuggestionsAppLibraryEnabled -bool NO {} ";"

👉 [Tips]Xcode13.1のSwiftUIのpreviewでCPU使用率が高くなるのをSpotlightを止めて回避する(iOS15) #iOS - Qiita hatena-bookmark

- Restart the computer and re-run xcrun simctl --set previews delete all
- Delete stored Preview data directly. This data is stored in ~/Library/Developer/Xcode/UserData/Previews.

👉 Use Realm with SwiftUI Previews — Realm hatena-bookmark


xcrun simctl --set previews delete unavailable | all

👉 SwiftUI Previews - Disk space issue | Apple Developer Forums hatena-bookmark

Save space by
1. xcrun simctl delete unavailable
2. xcrun simctl erase all
3. Delete /Users/username/Library/Developer/CoreSimulator folder.

👉 swiftui - Xcode 13 UI Previews folder takes too much space - Stack Overflow hatena-bookmark

 

📲 xcrun simctl とは ?

コマンドラインツールから help を確認する。


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

❯ xcrun simctl help delete
Delete specified devices, unavailable devices, or all devices.
Usage: simctl delete <device> [... <device n>] | unavailable | all

Specifying unavailable will delete devices that are not supported by the current Xcode SDK.

❯ xcrun simctl list devices
== Devices ==
-- iOS 17.0 --
    iPhone SE (3rd generation) (EE4D7500-5439-4D41-AD42-6028F649FA44) (Shutdown)
    iPhone 15 (984F204F-2D4E-4E56-8EEE-D11C46EDD9C2) (Shutdown)
    iPhone 15 Plus (C1349C55-57AC-4E47-9EF3-71A848E24A4E) (Shutdown)
    iPhone 15 Pro (04DC04FF-87DB-4EB6-91D8-C8CB4CF10015) (Shutdown)
    iPhone 15 Pro Max (5DC11544-4C3E-4852-8899-3D9E0844519B) (Shutdown)
    iPad Air (5th generation) (906B44B3-B298-4CF1-A5FB-0B4D43277636) (Shutdown)
    iPad (10th generation) (3804C1FA-6306-4CB7-98E0-D24CAFA70537) (Shutdown)
    iPad mini (6th generation) (351ED4C6-2DF3-4F1F-A29A-6D44483D9A95) (Shutdown)
    iPad Pro (11-inch) (4th generation) (96D48442-96AA-421A-BBA6-6F45EE8ECDBE) (Shutdown)
    iPad Pro (12.9-inch) (6th generation) (0B527419-DE2A-4146-93C4-55540B624C5C) (Shutdown)

❯ xcrun simctl --set previews list devices
Using Previews Device Set: '/Users/mao/Library/Developer/Xcode/UserData/Previews/Simulator Devices'
== Devices ==
-- iOS 17.0 --
    iPhone 15 Pro (676858D4-35E8-4841-91F4-17804B3E7565) (Shutdown)

覚えておくべきは、

Preview は、シュミレータ単独と別枠でシュミレータを使っている。

ということ。

 

📲 まとめ

Preview と シュミレーターに関連する問題は多そうです。

  • CPU 使用率
  • ストレージ占有
  • キャッシュ・データ不整合

私の場合スッキリ対応した方法としては、以下を Xcode を一旦終了して実行。


xcrun simctl --set previews delete all
rm -rf ~/Library/Developer/Xcode/UserData/Previews
rm -rf ~/Library/Developer/CoreSimulator/Caches

👉 How to clear/reset SwiftUI Preview Caches? hatena-bookmark

Behavors に入れときますか、消した previews に関しては自動で作成されると思って良さそう。


【JetpackCompose】 Composable 関数の Modifier について知らなかった3つのルール

【JetpackCompose】 Composable 関数の Modifier について知らなかった流儀

detekt に指摘されながら、ドキュメントを読む。


こんなコードがあったとして。


Column {
    InnerContent()
}

@Composable
private fun InnerContent() {
    Text(...)
    Image(...)
    Button(...)
}

以下、知らなかった流儀。

 

🧩 Composable 関数はレイアウトを一つだけ出力する

A composable function should emit either 0 or 1 pieces of layout, but no more. A composable function should be cohesive, and not rely on what function it is called from.

コンポーザブル関数は、レイアウトのピースを0個または1個だけ発行するべきで、それ以上は発行してはいけません。コンポーザブル関数は結束性を持ち、呼び出される関数に依存すべきではありません。

レイアウトのネストのコストはあまり気にしなくて良い、とのこと。

Nesting of layouts has a drastically lower cost vs the view system, so developers should not try to minimize UI layers at the cost of correctness.

レイアウトのネストには、ビューシステムに比べてはるかに低いコストがかかるため、UIの階層を正確性の犠牲にして最小化しようとしないべきです。

👉 Do not emit multiple pieces of content - Twitter Jetpack Compose Rules hatena-bookmark

ということで、一見不要に見える Column を追加する。


@Composable
private fun InnerContent() {
    Column {
        Text(...)
        Image(...)
        Button(...)
    }
}

 

🧩 デフォルトを持つパラメータ modifier: Nodifier = Modifier は必須

They are especially important for your public components, as they allow callers to customize the component to their wishes.

特に、公開コンポーネントにとって Modifier は非常に重要であり、呼び出し元がコンポーネントを希望に合わせてカスタマイズできるようにします。

👉 When should I expose modifier parameters? - Jetpack Compose Rules hatena-bookmark

Composables that accept a Modifier as a parameter to be applied to the whole component represented by the composable function should name the parameter modifier and assign the parameter a default value of Modifier.

Composable 関数内でコンポーザブル関数を表すコンポーネント全体に適用するための修飾子をパラメータとして受け入れる場合、そのパラメータは "modifier" という名前を付け、パラメータに Modifier のデフォルト値を割り当てるべきです。

👉 Modifiers should have default parameters - Jetpack Compose Rules hatena-bookmark

ということで、親からの Modifier を受け入れるようにします。デフォルト値もつけておきます。


@Composable
private fun InnerContent(modifier: Modifier = Modifier) {
    Column {
        Text(...)
        Image(...)
        Button(...)
    }
}

 

🧩 受け取った Modifier パラメータは最上位のレイアウトにのみ適用する

Modifiers should be applied once as a first modifier in the chain to the root-most layout in the component implementation. Since modifiers aim to modify the external behaviors and appearance of the component, they must be applied to the top-most layout and be the first modifiers in the hierarchy. It is allowed to chain other modifiers to the modifier passed as a param if needed.

Modifier は、コンポーネントの実装内でルートのレイアウトに最初の Modifier として一度適用すべきです。Modifier はコンポーネントの外部の動作や外観を変更することを目的としているため、最上位のレイアウトに適用し、階層内で最初の Modifier である必要があります。必要に応じて、パラメータとして渡された Modifier に他の Modifier を連鎖させることは許可されています。

👉 Modifiers should be used at the top-most layout of the component - Jetpack Compose Rules hatena-bookmark

ということで、最上位ルートの Column で適用します。


@Composable
private fun InnerContent(modifier: Modifier = Modifier) {
    Column(modifier = modifier) {
        Text(...)
        Image(...)
        Button(...)
    }
}

 

🧩 まとめ

@Composable 内のレイアウトに関する Modifier は、親 (呼び出し元) から持ってきて、最上位のレイアウトで一度だけ適用する。

detekt を使うことで、なんとなく記述していた部分がスッキリしてきます。

👉 【AndroidStudio】detekt で JetpackCompose 記述をチェックする hatena-bookmark


【AndroidStudio】実行時に自動でそれまでのログを消して logcat ウインドウを開く設定

こういう設定があるのは知っているけど設定をどこでするのか毎回分からない、ので。


[Run]

  ↓

[Edit Configulations...]

  ↓

✅ [Show logcat automatically]
✅ [Clear log before launch]


✔[Show logcat automatically]
✔[Clear log before launch]

基本的にこの2つはONにしてていいと思います。


【Android】TextField フォーカスを利用した IME 開閉が Material3 で壊れたので修正していく

Material3 に改修してみると、

こんなかんじに入力欄とIMEの挙動がおかしくなったので、

2023年8月31日以降 アプリは Android 13(API レベル 33)以降を対象にする必要があります。
2023年9月26日
Jetpack Compose Dependency versions API-33 vs API-34
2023年9月23日
メモリーリークを防ぐには欠かせない Lifecycle Observer は remove/unregister 不要
2023年9月10日
Gson が R8 で落ちる
2023年8月28日
【Kotlin DSL】Deprecated な packagingOptions が fun Packaging.() に変換される件
2023年8月27日
【Android】通知が表示されないときのアプリ別の端末設定 ON/OFF ⚙️
2023年8月25日
Missing classes detected while running R8. Please add the missing classes or apply additional keep rules that are generated in /app/build/outputs/mapping/debug/missing_rules.txt
2023年8月24日
Unresolved reference: BuildConfig
2023年8月16日
ログインに使っている Twitter (X) アカウントの連携を削除する手順
2023年8月11日
【iPhone】Yahoo天気アプリ 「現在地ボタンが変わりました」は「現在地ボタンは無くなりました」では?
2023年8月10日
【Mac】絵文字 や GitHubショートコード は「GitHub Emoji Picker」で入力する 😀
2023年8月9日
ChatGPT クローラー の UA(ユーザーエージェント) と IPアドレス範囲 まとめ
2023年8月4日
Android OS version market share
2023年7月30日
【iPhone】「パケ詰まり」「パケ止まり」を修復するショートカット 📱
2023年7月26日
Android Studio Giraffe | 2022.3.1 の dependencies の揃え方
2023年7月24日
将来、URL の twitter.com は x.com となるんだろうか。
2023年7月20日
Service Locator と DI どちらを使うか、という話。
2023年7月13日
【iPhone/Android】富士山 にいくなら「富士山」アプリ 🏔
2023年7月12日
Chromecast の 素晴らしい背景画面 をダウンロードできる件
2023年7月11日
スマホスタンド(充電不可)を作ってみたが、まあまあ使っている 📱
2023年7月10日
【Android Studio】[File] - [Project Structure] - [Suggestions] で「Update」する dependencies の妥当性 💉
2023年7月7日
【WordPress】自分のブログで「無効なトラフィック」を発生させないための Adsense タグ記述
【Jetpack Compose】TextField の フォーカス と IME 開閉 と カーソル位置

以下を元に少し見直していきます。

👉 【Jetpack Compose】TextField の フォーカス と IME 開閉 と カーソル位置 hatena-bookmark

(更新中...)


【macOS】gnubin への PATH を一括で通す

【macOS】GNU パッケージの PATH
GNU gsed をインストールした後の表示。


GNU "sed" has been installed as "gsed".
If you need to use it as "sed", you can add a "gnubin" directory
to your PATH from your bashrc like:

     PATH="$HOMEBREW_PREFIX/opt/gnu-sed/libexec/gnubin:$PATH"

👉 gnu-sed — Homebrew Formulae hatena-bookmark

sed のように利用するには PATH を優先しておく、とのことだが。

GNU パッケージは、「パッケージごとに」シンボリックシンクが分かれている。


Commands also provided by macOS and the commands dir, dircolors, vdir have been installed with the prefix "g".
If you need to use these commands with their normal names, you can add a "gnubin" directory to your PATH with:
    PATH="$HOMEBREW_PREFIX/opt/coreutils/libexec/gnubin:$PATH"

👉 coreutils — Homebrew Formulae hatena-bookmark

自分のマシンで見てみる。


❯ ls -l $(brew --prefix)/opt/*/libexec/gnubin
/opt/homebrew/opt/gnu-sed/libexec/gnubin:
total 0
lrwxr-xr-x@ 1 mao  admin  14 Nov  7  2022 sed@ -> ../../bin/gsed

/opt/homebrew/opt/gsed/libexec/gnubin:
total 0
lrwxr-xr-x@ 1 mao  admin  14 Nov  7  2022 sed@ -> ../../bin/gsed

/opt/homebrew/opt/libtool/libexec/gnubin:
total 0
lrwxr-xr-x@ 1 mao  admin  18 Mar 17  2022 libtool@ -> ../../bin/glibtool
lrwxr-xr-x@ 1 mao  admin  21 Mar 17  2022 libtoolize@ -> ../../bin/glibtoolize

そうか、インストール時に作ってくれてるんだシンボリックリンク。

sed@ が2個あるけど実体は同じでした。


❯ ls -al /opt/homebrew/opt/gnu-sed
lrwxr-xr-x@ 1 mao  admin  21 Oct  5 22:58 /opt/homebrew/opt/gnu-sed@ -> ../Cellar/gnu-sed/4.9

❯ ls -al /opt/homebrew/opt/gsed
lrwxr-xr-x@ 1 mao  admin  21 Oct  5 22:58 /opt/homebrew/opt/gsed@ -> ../Cellar/gnu-sed/4.9

よって、以下のようにして GNU パッケージの PATH を一括で通すと良い、とな。


if type brew &>/dev/null; then
  HOMEBREW_PREFIX=$(brew --prefix)

  # gnubin; gnuman
  for d in ${HOMEBREW_PREFIX}/opt/*/libexec/gnubin; do export PATH=$d:$PATH; done

  # I actually like that man grep gives the BSD grep man page
  #for d in ${HOMEBREW_PREFIX}/opt/*/libexec/gnuman; do export MANPATH=$d:$MANPATH; done
fi

👉 macos - Homebrew: Easy way to add 'gnubin' to path for multiple packages? - Ask Different hatena-bookmark

他パッケージのインストーラーがこけたりするときないのか、と思ったので眺めておきました。