如果唯一的目的是为不同的环境设置不同的值 - development, QA, UAT, Production
,xcconfig
可以使用文件。
不需要条件语句,但根据配置,它将采用适当的值。
所涉及的步骤是:
添加不同的架构和不同的构建配置。
通过选择 File->New->File and "Configuration Settings file"
-> Development.xcconfig, UAT.xcconfig, Production.xcconfig
etc添加配置设置文件
![在此处输入图像描述](https://i.stack.imgur.com/bBDfi.png)
在配置文件中添加您选择的自定义键,并在键值对中添加它们的相关值:
endpointUrl = "Production_Url"
用于生产.xcconfig
endpointUrl = "UAT_Url"
对于 UAT.xcconfig
![在此处输入图像描述](https://i.stack.imgur.com/wyQLj.png)
- 添加相关的 plist 文件并将 .xcconfig 文件中的密钥添加到 .plist 文件中。为 UAT.xcconfig 文件创建 UAT.plist 并为其他支持的配置创建类似的方式。
![在此处输入图像描述](https://i.stack.imgur.com/bH7C9.png)
- 在下为每个构建配置设置适当的 plist 路径
Project -> Info -> Configurations
![在此处输入图像描述](https://i.stack.imgur.com/amJsv.png)
- 创建一个 .swift 文件来读取配置文件,例如:
公共枚举 PlistKey { case EndpointURL
func value() -> String {
switch self {
case .EndpointURL:
return "endpointUrl"
}
} }
公共结构环境{
fileprivate var infoDict: [String: Any] {
get {
if let dict = Bundle.main.infoDictionary {
return dict
}else {
fatalError("Plist file not found")
}
}
}
public func configuration(_ key: PlistKey) -> String {
switch key {
case .EndpointURL:
return infoDict[PlistKey.EndpointURL.value()] as? String ?? "noValue"
}
}
}
- 将网址称为:
let server_url = Environment().configuration(PlistKey.EndpointURL)
更详细的版本在:https ://www.freecodecamp.org/news/managing-different-environments-and-configurations-for-ios-projects-7970327dd9c9/