美文网首页小斑iOS-swift
Swift3.0项目--不同target设置不同环境变量

Swift3.0项目--不同target设置不同环境变量

作者: 亼仐 | 来源:发表于2016-12-09 10:17 被阅读124次

为什么需要这么做?

在实际项目开发中,经常需要根据不同环境设置不的配置变量。比如接口 BaseUrl,环境变量等。

Objective-C项目中一般如何处理

1.思路

  • 为项目建立不同的TARGETS
  • 针对不同TARGETSPreprocessor Macros 设置不同的宏定义
  • 针对不同的宏定义配置不同的环境变量

2.步骤

步骤图

接下来就是针对Preprocessor Macros的自定义宏在配置文件定义不同的环境变量

#ifdef HITAO_PRODUCT        //线上环境

#define DEFAULT_SERVER      @"https://api.zl.com"
#define DEFAULT_PATH        @""
#define DEFAULT_END_POINT   @"/"
#define APP_KEY             @""
#define APP_SECRET          @""
#define HTML_BASEURL        @""

#elif HITAO_TEST   //测试环境

#define DEFAULT_SERVER      @"https://testapi.zl.com"
#define DEFAULT_PATH        @""
#define DEFAULT_END_POINT   @"/"
#define APP_KEY             @""
#define APP_SECRET          @""
#define HTML_BASEURL        @""

#else         //

#endif

3.使用

这样一次配置之后,针对不同环境进行测试,执行切换不同的Targets再编译就行。是不是很方便呀

target切换

Swift项目中一般如何处理

1.问题

我们知道,Swift不像OC是基于C实现的,因此中并没有预处理,宏定义这些特性。但这样,我们如何实现前文中的效果。答案是可以的,Swift提供Swift Flags同样可以实现。

2.实现

Build Settings 中搜索Other Swift Flags

Other Swift Flags

然后就就这个Swift Flags进行不同环境的定义,Swift虽然没有#define, 但是也有替代方式#if Pro_Test #endif

#if Pro_PRODUCT
//线上环境
let DEFAULT_SERVER = "https://api.zl.com"
let 其他变量  = 'xxxxxxxxxxxx'
#endif

#if Pro_Test
//测试环境
let DEFAULT_SERVER = "https://testapi.zl.com"
let 其他变量  = 'xxxxxxxxxxxx'
#endif

3.使用

使用方式和Objective-C一样,我就不再累赘了哟~


能不能有点专业精神!《喜剧之王》

相关文章

网友评论

    本文标题:Swift3.0项目--不同target设置不同环境变量

    本文链接:https://www.haomeiwen.com/subject/redemttx.html