本項目包含 “iOS App配置多環境變量 + 使用fastlane快速打包并上傳蒲公英/AppStore”
GitHub:MultipleEnvironment
參考
需求:切換以下功能時無需修改代碼
- 切換服務器時。
- 開發、測試環境下的 “分享、統計” 等功能 使用開發渠道統計數據,上線后才使用線上渠道統計。
- 開發、測試環境顯示全部功能,而正式上線時需服務端控制該功能的顯示/隱藏(例如:躲避蘋果的支付審核,測試環境下允許支付寶、微信、蘋果內購 3種支付方式,而審核時只顯示蘋果內購支付)(注:千萬不要試圖躲避內購,否則蘋果生氣了后果很嚴重,親身體驗)
定義三個項目環境變量。
- dev: 開發
- adhoc: 測試
- appstore: 線上
可選方案:
- 利用Build Configuration來配置多環境
- 利用xcconfig文件來配置多環境
- 利用Targets來配置多環境
配置步驟:
根據本項目需求,采用最簡單輕量級的方案 "Build Configuration" 來配置多環境。
-
為 "dev", "adhoc", "appstore" 3種環境分別創建 Debug、Release版的Configuration。
- 在Xcode的 Project 里面找到 Configurations。
- dev: 將"Debug"改名為"dev-debug",將"Release"改名為"dev-release",
- adhoc: 點擊 "+" -> "Duplicate Debug Configuration",改名為 "adhoc-debug", 再點擊 "+" -> "Duplicate Release Configuration" 改名為 "adhoc-release"。 這里使用 Duplicate,如果項目已經安裝過cocoapods,則會把對應 Debug、Release環境下的配置一并拷貝過來。
-
appstore: 同"adhoc"。
注意:如果使用了cocoapods,完成后需要pod install一下。
configurations_1.jpg
configurations_2.jpg -
選中 "對應的Target" -> "Build Settings" -> "Active Compilation Conditions(Swift版,如果是OC,則是Preprocessor Macros)" 為不同環境配置不同的宏定義。(系統默認已在Debug環境下帶有“DEBUG”標志)
- dev-debug: DEBUG dev
- dev-release: dev
- adhoc-debug: DEBUG adhoc
- adhoc-release: adhoc
- appstore-debug: DEBUG appstore
- appstore-release: appstore
這樣做比較靈活,項目中就可以自由組合 DEBUG、dev、adhoc、appstore 來判斷環境條件了。
compilation_conditions.jpg -
配置Scheme。
- 新建3個Scheme,"New Scheme", 名字可以為“工程名+ dev、adhoc、appstore等后綴”,自己看得懂就行。
- 創建后要勾選shared選項,這樣該scheme才會加入到git中,與他人共享,然后可以刪掉最開始那個無用的Scheme了。
- "Edit Scheme",需要為每個Scheme的 "Run", "Test", "Archive"... 之類的 配置 "Build Configuration",按需選則對應的。
例如 系統默認對應的 Debug、Release如下
dev: "Run" - "dev-debug"
"Test" - "dev-debug"
"Profile" - "dev-release"
"Analyze" - "dev-debug"
"Archive" - "dev-release"
代碼中的使用:
- 配置不同服務器地址
#if dev
let ServerURL = "http://aaa.com"
#elseif adhoc
let ServerURL = "http://bbb.com"
#elseif appstore
let ServerURL = "http://ccc.com"
#endif
- 開發、測試環境下,配置渠道。
#if dev || adhoc
channel = "development"
#else
channel = "appstore"
#endif
- Debug && dev環境下添加額外功能
#if DEBUG && dev
// add some feature
#endif
使用:
需要切換環境時,直接選中對應的Scheme,run就好了。
補充:
如果想在同一部手機上安裝多個不同環境下的相同App,可選擇 "對應Target" -> "Build Settings" -> "+" -> "Add User-Defined Setting" 為不同Scheme配置不同包名、應用名、應用圖標等,但是要注意,如果App里中有和 包名bundle Id相關的配置,則要小心了,例如推送證書,它指定推送到對應bundle id的應用上(親身踩坑)。 此時簡單的使用 "Build Configuration" 則無法滿足需求,可選擇 多Targets來配置多環境、多證書之類。
fastlane自動打包上傳
使用fastlane快速打包并上傳蒲公英/AppStore這篇文章寫得非常清晰詳細了。我的fastlane配置文件已經在項目中了 /fastlane/Fastfile。更多fastlane的actions信息可以在fastlane actions文檔中查看
在項目根目錄下使用:
- "fastlane dev": 打開發環境的包并上傳蒲公英
- "fastlane adhoc": 打測試環境的包并上傳蒲公英
- "fastlane release": 打正式包并提交到"https://appstoreconnect.apple.com"上。
其中 "fastlane release"正式包還需配置/fastlane/Appfile中的 "App Store Connect Team ID"和"Developer Portal Team ID"。(注意這里使用 release而不是appstore字段,是因為appstore字段已經被fastlane作為其他用途了)
補充:打包后,在項目根目錄下會出現 ipa包,它已被.gitignore忽略,并且 每次打新包都會自動覆蓋舊ipa包。通過fastlane打的包也會出現在 Xcode的Organizer中.
使用Jenkins持續集成
本項目未使用,可參閱利用Jenkins持續集成iOS項目