iOSアプリを開発していて、アプリの画面内にバージョン情報を表記することがあると思います。
この際、gitのcommit hashを表示したかったので、方法をまとめました。
こんな感じでバージョン情報を表記できます。
1.0.0_d6d4de6
Xcodeのバージョンは Version 11.4 (11E146)
です。
Info.plistの編集
Info.plist
に CommitHash
というkeyを追加します。
valueには undefine
というStringを入れておきます。
Build Settingsの編集
Build Settings の Preprocess Info.plist File
を YES
に変更します。
Build Phasesの編集
Build Phases の Compile Sources
の前に Run Script Phase
を追加します。
今回は Get Commit Hash
という名前で作成しています。
コマンドは下記を追加します。
plistBuddy="/usr/libexec/PlistBuddy"
infoPlistFile="${TEMP_DIR}/Preprocessed-Info.plist"
commitHash=$(git rev-parse --short HEAD)
$plistBuddy -c "Set :CommitHash $commitHash" $infoPlistFile
Input Filesの項目に
${TEMP_DIR}/Preprocessed-Info.plist
を設定します。
コードからバージョン情報とcommit hashを呼び出す
swiftのコードからバージョン情報とcommit hashを呼び出すには下記のようにします。
let info = Bundle.main.infoDictionary!
let versionName = "\(info["CFBundleShortVersionString"]!)_\(info["CommitHash"]!)"
以上です!