一般我們開發(fā)完新的版本,準備提交到AppStore審核的時候,我們需要把項目里的指向測試環(huán)境的URLs和API Keys切換到正式環(huán)境。每次都是如此很累而且容易出錯。
以往我們處理這種問題會通過類似的方法
enum environmentType {
case development, production
}
let environment:environmentType = .production
switch environment {
case .development:
// set web service URL to development
// set API keys to development
print("It's for development")
case .production:
// set web service URL to production
// set API keys to production
print("It's for production")
}
這樣處理之后情況好了很多,我們在提交審核的時候只需要更改這個全部變量為正式環(huán)境。
但是這個時候如果我們想要在同一個設備上同時安裝測試版本和正式版本,我們還需要更改bundle ID,我們安裝的版本沒法很明顯區(qū)分到底是測試版本還是正式版,問題又來了。
那么小伙伴們不用擔心,下面我們一步一步來學習怎么使用Xcode的Targets完成這個任務
-
How to Create a New Target
1.創(chuàng)建Target

2.選擇Duplicate Only

如果你的項目Device是universal devices,Xcode不會出現(xiàn)這個對話框。
3.對新建的Target重命名
- 選中新建的
Target按下Enter編輯名稱,我比較喜歡 '項目名稱 Dev' - 然后去
Manage Schemes…,選中剛才創(chuàng)建的‘scheme’按下Enter修改為何剛才Target一樣的名字

4.這一步不是必須的,但是強烈推薦,因為這一步我們可以很容易區(qū)分測試和線上版本從App圖標
- 選中
Assets.xcassets,給Target Dev添加圖標
添加Dev圖標
5.返回項目設置,選擇Target Dev改變bundle identifier,這樣我們就可以同時安裝開發(fā)和生產(chǎn)環(huán)境的包了,然后設置啟動圖標為第4不添加的icon

6.Xcode在我們第一步創(chuàng)建Target的時候就同時創(chuàng)建了一個xxx info.plist的副本,修改名字為 項目名稱-Dev
7.打開Target Dev 的 Build Settings,找到Packaging

8.配置全局宏,分為OC和Swift(網(wǎng)上找的)
- For Objective-C projects, go to Build Settings
and scroll to Apple LLVM 7.0 - Preprocessing
. Expand Preprocessor Macros
and add a variable to both Debugand Release fields. For the development target (i.e. todo Dev), set the value toDEVELOPMENT=1
. On the other hand, set the value to DEVELOPMENT=0
to indicate a production version.
OC -
For Swift project, the compiler no longer supports preprocessor directives. Instead, it uses compile-time attributes and build configurations. To add a flag to indicate a development build, select the development target. Go to Build Settings
and scroll down to the Swift Compiler - Custom Flags
section. Set the value to -DDEVELOPMENT
to indicate the target as a development build.
Swift
9.使用方法,分為OC和Swift
- Objective-C:
#if DEVELOPMENT
#define SERVER_URL @"http://dev.server.com/api/"
#define API_TOKEN @"DI2023409jf90ew"
#else
#define SERVER_URL @"http://prod.server.com/api/"
#define API_TOKEN @"71a629j0f090232"
#endif
- Swift:
#if DEVELOPMENT
let SERVER_URL = "http://dev.server.com/api/"
let API_TOKEN = "DI2023409jf90ew"
#else
let SERVER_URL = "http://prod.server.com/api/"
let API_TOKEN = "71a629j0f090232"
#endif
10.現(xiàn)在當你選擇’項目名稱 Dev‘ scheme運行,Xcode就會用你定義的去配置為開發(fā)環(huán)境,你可以直接上傳到TestFlight 或者其他測試平臺。
如果你想切換到生產(chǎn)環(huán)境,只需要切換到 ’項目名稱‘cheme,不需要修改任何代碼,是不是很爽??
對于多Targets需要注意的
1. 當你給項目添加文件的時候,別忘了把文件同事包含到Dev Target中,讓代碼同步

2.如果你是使用Cocoapods來管理依賴,需要把Target Dev添加到podfile中。
語法可能會改變具體查看Cocoapods文檔
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '7.0'
workspace 'todo'
link_with 'todo', 'todo Dev'
pod 'Mixpanel'
pod 'AFNetworking'


