5

Xcode 使用 Configuration 来配置不同的项目环境

 2 years ago
source link: https://www.isaced.com/post-276.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Xcode 使用 Configuration 来配置不同的项目环境

很多项目在开发时都会经常在开发环境和生产环境之间切换,切换随之伴来的还有比如更换 App 名称、Bundle identitier、服务端接口地址等等相关参数和属性,这个时候我们就可以利用 Xcode 提供的 Configuration 来配置不同的环境,从而进行快速切换、编译等等一系列操作。

xcode_ configuration_list

注: Xcode 中 Build Settings 的所有项都可以针对不同的 Configuration 设置不同的值

使用不同的环境配置进行调试

定义好不同的环境后,你就可以分别设置 runtestArchive… 这些操作分别使用哪一个 Build Configuration 进行编译,从而可以很轻松得分离开各个配置环境的设置。比如分离不同的服务端开发和正式环境,就可以利用宏定义进行参数区分(参见后文)轻松实现,然后开发的时候需要切换环境测试之类的就可以直接在 Edit Scheme 里修改对应的 Configuration,不用再修改代码。

edit_scheme

切换不同的 Bundle identifier

在 Targets -> Build Settings -> Packaging -> Product Bundle Identifier 中设置不同的值即可。

切换不同的 App Name

如果需要实现根据 Configuration 设定不同的应用显示名称,可以通过增加 User-Define 属性实现,甚至可以直接使用 *Product Name*,这里说一下前者的设置方法。

在 Targets -> Build Settings 顶部 “+” 按钮弹出菜单中选择 “Add User-Defined Setting” 来增加一项 User-Defined 属性,值可以自己随意设定,名称可以叫 “BUNDLEDISPLAY_NAME”,然后在 “xxx-Info.plist” 中的 Bundle display name 项中设置值为 ${BUNDLE_DISPLAY_NAMEAA},搞定!

利用宏定义进行参数区分

如果想在代码中对不同环境进行各自的参数加载或者操作处理,我们可以通过预处理宏来判断,通过给 Configuration 增加宏定义和 #ifdef 预处理命令就可以实现。

比如我们要给一个名为 DebugBeta 的 Configuration 设定加载非正式环境的服务端接口地址,在 Targets -> Build Settings -> Preprocessor Macros 中给 DebugBeta 设定一个特殊标识就行了,比如 “BETASERVERURL=1”。

然后通过预处理代码进行判断就可以实现加载不同的参数项,比如还可以设定一些 SDK 区分正式/开发环境的 Key,做一些非常灵活的操作。

NSString *serverURL;
#ifdef BETASERVERURL
    serverURL = @"http://xxx";
#else
    serverURL = @"http://yyy";
#endif

Cocoapods 可能会遇到的问题

定义好自己的 Configuration 后,再执行 pod install 可能会遇到类似下面的警告信息,这个时候只需要在 Project -> Info -> Configurations 中自定义的配置 ‘Based on Configuration File’ 设为 None 就可以了。

[!] CocoaPods did not set the base configuration of your project because your project already has a custom config set. In order for CocoaPods integration to work at all, please either set the base configurations of the target 项目名 to Pods/Target Support Files/Pods-项目名/Pods-项目名.release.xcconfig or include the Pods/Target Support Files/Pods-项目名/Pods-项目名.release.xcconfig in your build configuration.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK