【iOS开发】设置多个schemes和configurations来实现应用环境的切换

1,102 阅读3分钟

在开发过程中,我们一般会先在测试环境进行开发,确保功能没问题之后才放到生产环境。在测试和生产环境切换的过程中,我们通常要切换第三方SDK的API key、服务器的域名等等。

我看到有些应用是这么做的:在应用目录里面用两个plist文件来存储各种API key和域名之类的,一个存储测试环境,另外一个存储生产环境的。这种方法会引发应用的安全问题,其他人可以查看你的plist文件,造成信息泄露。

事实上,我们可以通过设置多个 schemes 和 configurations来更方便的进行应用环境的切换。请继续往下看,我们是如何设置的。

一、添加configurations

  • 选择Project -> info -> 点击Configurations下面的加号
  • 选择 Duplicate Debug Configuration,命名为Debug Staging
  • 选择 Duplicate Release Configuration,命名为Release Staging

这里我们新建了Debug StagingRelease Staging两个配置,用于测试环境。原有的DebugRealse用于生产环境。

添加configurations

添加configurations

二、添加自定义变量

  • 选择Target -> Build Settings -> 点击下面的加号
  • 选择 Add User-Defined Setting

添加自定义变量

  • 把变量命名为IS_STAGING,并根据下图设置对应的值:其中Debug StagingRelease Staging设置为YES,其他两个设置为NO。后续我们在运行的时候,就可以根据他们的值来判断当前运行的是测试和生产环境。等会会讲到如何获取他们的值。除此之外,我们可以添加其他需要区分生产和测试的变量。

添加自定义变量

三、创建测试环境的Scheme

  • 点击Scheme,并选择Manage Schemes

创建测试环境的Scheme

  • 点击加号,把测试环境的Scheme命名为MultipleSchemesAndConfigurationsDemo_Staging

创建测试环境的Scheme

  • 把后面的shared勾上,然后点击close

创建测试环境的Scheme

  • 确保选中了MultipleSchemesAndConfigurationsDemo_Staging,然后点击Edit Scheme

Edit Scheme

  • 1)选择左边的Run -> Info -> Build Configuration,设置为Debug Staging。意思是说在我们直接在Command + R运行的MultipleSchemesAndConfigurationsDemo_Staging的时候,使用Debug Staging这个配置;类似的,我们把: 2)TestAnalyze设置为Debug Staging;3)ProfileArchive设置为Release Staging

Edit Scheme

四、获取自定义变量

我们刚刚在Build Settings设置了YES和NO,我们可以通过Info.plist来获取。

  • 添加一个字段,命名为IS_STAGING,值为$(IS_STAGING)。运行的时候,系统会根据当前运行的Scheme配置来最终确定它的值。

获取自定义变量

  • 读取IS_STAGING

通过以下代码获取我们的自定义变量

if let isStaging = Bundle.main.infoDictionary?["IS_STAGING"] as? String {
    if isStaging == "YES" {
        // 测试环境相关代码
    } else {
        // 生产环境相关代码
    }
}

五、环境的管理

在开发过程中,我们可以新建一个类EnvironmentManager来管理生产和测试环境相关的问题。例如,我们通常会用到一些第三方的SDK,例如统计和分享之类的,可以把他们的初始化统一放在这里。

代码如下:

/// 应用的环境
enum AppEnvironment {
    case staging
    case production
}

final class EnvironmentManager {

    /// 使用单例
    static let shared = EnvironmentManager()

    /// 当前环境
    static var currentAppEnvironment: AppEnvironment = .staging

    /// 是否是测试环境
    static var isStaging: Bool {
        return currentAppEnvironment == .staging
    }


    /// 把环境初始化相关代码放到这里,然后在AppDelegate中调用这个方法
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {

        // 获取我们在Build Settings设置好的自定义变量
        // 根据变量来判断当前的运行环境
        if let isStaging = Bundle.main.infoDictionary?["IS_STAGING"] as? String {
            if isStaging == "YES" {
                EnvironmentManager.currentAppEnvironment = .staging
            } else {
                EnvironmentManager.currentAppEnvironment = .production
            }
        }

        // 初始化其他SDK
        initializeOtherSDK()
    }

    private func initializeOtherSDK() {

    }
}

六、总结

以后我们就可以通过选择不同的Scheme来切换测试和生产环境,非常方便。

切换Scheme

如果有错误的地方,欢迎指正!谢谢!