首页 > 解决方案 > Switching between test and real url using conditional statement in swift

问题描述

I want to use local urls for testing. How do I switch between test and real url at compile time?

I'm aware of Active Compilation Conditions but I don't want to use that as it's debug/release thing. I want to switch between test and real urls whenever I wish during my development phase and testing. To do so I want to have a flag which I can change before compilation.

Here is what I want to achieve, it's a pseudo code.

#define TEST=TRUE (or FALSE)

#if TEST
static let URL = "http://127.0.0.1/api/"
//... other code
#else
static let URL = "https:// domain.com/api/"
//... other code
#endif

标签: iosswiftxcode

解决方案


好的,那么如果您希望能够在开发期间更改 URL 而无需进行新构建,您有不同的选择,但快速的选择始终是隐藏的配置弹出窗口或菜单,您可以在登录或其他任何操作之前从第一个屏幕访问它。

隐藏菜单出现在哪里:是您想要决定的事情,但也许,在启动 ViewController 或入职或登录的某个地方,您想添加一个手势识别器以显示您的隐藏菜单,假设在您的任何地方双击ViewController.view它将仅在 Debug 构建中显示隐藏的配置警报,而不是在登录或任何相关 api 调用之前的发布:

#if DEBUG
    let tap = UITapGestureRecognizer(target: self, action: #selector(presentHiddenConfigurationAlert))
    tap.numberOfTapsRequired = 2
    view.addGestureRecognizer(tap)
#endif

隐藏菜单的外观和行为方式:现在以及在同一个 ViewController 中(例如在我的示例中,LoginVC 或任何您想要的),您将在双击时使用选择器方法,例如显示警报这可以让您更改当前的 url(与往常一样,这只能在 Debuggable 构建中发生):

#if DEBUG
@objc func presentHiddenConfigurationAlert() {
    let currentURL = UserDefaults.string(forKey: "current_url")

    let alertView = UIAlertController(title: "Hidden Configuration", message: "You are using \(currentURL)", preferredStyle: .alert)

    // add a textview to let developer input the url he wants to use as an action

    // or add some actions as buttons to choose between a Test URL button action and Dev URL button action

    // store the URL as of "current_url" so you can retrieve it in an instance used across the app and here in the message

    self.present(alert, animated: true, completion: nil)
}
#endif

总体而言,在我的示例中,用例是:

  • 您安装了应用程序并处于可调试版本中
  • 登录视图控制器是显示的第一件事(例如)
  • 您或其他使用此构建的开发人员双击此视图控制器中的任何位置
  • 显示隐藏的菜单警报配置,您可以在其中更改在应用程序中使用的当前 URL
  • 您将此 URL 存储在用户默认值或您最喜欢的位置
  • 现在无论您在哪里访问 URL 变量,您都希望在调试中使用用户默认值中的变量,而在发布中使用发布版本
#if DEBUG
var API_URL = getURLFromUserDefaults()
#else
var API_URL = "https://www.release-product-url.com"
#endif

推荐阅读