做版本更新提示、資料上報或埋點時,往往需要讀取 App 自身的基本資訊。這些值都存在 Info.plist 裡,透過 NSBundle 就能拿到。
1. Bundle Identifier
[[NSBundle mainBundle] bundleIdentifier];
2. 版本號(CFBundleShortVersionString)
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
這是給使用者看的版本號,例如 1.2.0。
3. Build 號(CFBundleVersion)
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
這是給系統與上傳流程用的建置序號,每次上傳 App Store Connect 都必須遞增。
4. App 顯示名稱(CFBundleDisplayName)
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
其實 [[NSBundle mainBundle] infoDictionary] 拿到的就是一個字典,內容正是 Info.plist 的全部鍵值。知道鍵名就能取值,常見的還有:
CFBundleDevelopmentRegion CFBundleDisplayName CFBundleExecutable CFBundleExecutablePath CFBundleIdentifier CFBundleInfoDictionaryVersion = "6.0"; CFBundleInfoPlistURL CFBundleName CFBundlePackageType CFBundleShortVersionString CFBundleSignature CFBundleSupportedPlatforms
小技巧:把版本號與 Build 號合併成一個字串(如 1.2.0(88))顯示在設定頁或除錯面板,回報問題時會省下不少溝通成本。另外,Swift 中對應的寫法是 Bundle.main.infoDictionary 與 Bundle.main.bundleIdentifier。