在开发过程中,我们通常要在多个环境工作比如开发环境或者生产环境。这些环境往往有几个不同的参数,比如server hostname, Bundle ID和第三方库的 API key。
之前,我会手动的在多环境下工作。这就意味着我需要手动替换Bundle ID,API key和server URL。这样做相当浪费时间,而且是没有必要的。
下面我会教大家解决这个问题,轻松切换不同的构建环境。我们将会使用到 Xcode Scheme,Build Configuration 和 Build Settings 去管理不同的builds。
第一步:创建Build Configurations
首先,来到项目信息页面。选择PROJECT并找到Configurations部分。打开你的Configurations选项将有一个Debug选项和Release选项里面。

然后点击+号按钮 并选择duplicate the "Debug" configuration创建一个新的configuration.

对新创建的configuration重命名,这里我重命名为Debug Staging

重复以上操作,我们选择duplicating theReleaseconfiguration再创建2个不同的builds:Release StagingandApp Store .好了,最后我们将会拥有5个不同的build configurations.

第二步:创建User-defined Build Settings
通常,我们将创建一个用户自定义设置BundleID、app icon names,Facebook App ID等等。所以我们可以分配不同的BundleID、app icon names,Facebook App ID不同的构建配置。为此,导航到项目构建设置,单击Add按钮(+)和添加用户定义的设置。

在下面的例子中我会创建3个不同的User-defined Build Setting,BUNDLE_ID,NAME_SUFFIX和FB_APP_ID.并为其设置不同的值,如下图:

第三步:修改 Info.plist 文件
在上一步中定义的所有用户定义的设置将用于项目的info.plist。确保你已经做了前面的步骤之后再继续。修改你的Info.plist文件插入用户自定义设置中定义的值。例如,你在User-defined Build Setting中定义了BUNDLE_ID,那么你要在Info.plist中修改你的Bundle ID信息。如下:
$(BUNDLE_ID).
Bundle Identifier : $(BUNDLE_ID)
Bundle display name: Demo App $(NAME_SUFFIX)
FacebookAppID: $(FB_APP_ID)
其中FacebookAppID在Info.plist文件中并没有出现,我们可以新增一个字段。

第四步:为Build Configurations创建Schemes
每一个 app build 都需要一个Schemes,所以我们需要创建3个Schemes,分别是DemoAppStaging,DemoAppProduction和DemoAppStore。点击您的项目active scheme,它就位于左上角的编辑器,点击“manage scheme”。如果你不能找到它请参考下面的图片。

然后,创建新的Scheme命名为DemoAppStaging

重复以上操作,创建DemoAppProduction和DemoAppAppStore。请确保你选上了Shared选项,因为这将影响你的这些操作是否被加进git的仓库。

第五步:编辑 Schemes
然后,基于不同的build configurations编辑schemes。例如,DemoAppStaging使用Debug Staging和Release Staging Build configurations。确保你有为build configurations编辑Build,Run,Test,Profile,Analyze和Archive。

如下表所示编辑3个Schemes

现在,我们可以很容易地切换不同的builds了。

注意:如果你之前已经引入过一些第三方库的话,程序运行时可能会提醒你无法识别这些第三方库。因为你的第三方库只是引入到了Debug和release环境中,我们新加的build Configurations中并没有引入第三方库。所以我们需要将这些第三方库也加入到新加的build Configurations中。(在终端输入cd 工程路径,利用cocoaPods下载类库,在终端输入 pod install 开始安装)完成之后的效果如下图所示

第六步:根据不同环境选择参数值
在target下 Build Settings 搜索 Other Swift Flags,设置Debug 添加 -D DEBUG,注意不要好Release一起添加

下面的代码是我的另一个项目针对swift语言写的,oc语言下也一样

遇到的问题:在使用过程中我的第三方库会报错,如下:

解决方案入下:选中Pods中TARGETS中报错的第三库,选择Build Settings,搜索use legacy。将Use Legacy Swift Language Version的值改为NO。

希望我的分享能帮助到你!
参考:
1. http://www.teratotech.com/blog/xcode-7-steps-to-easily-switch-between-multiple-environments/
2. http://blog.csdn.net/aaaa99996666/article/details/53006358
3. http://www.th7.cn/Program/IOS/201512/713814.shtml
网友评论