如何在 Xcode 6 中访问构建设置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24645090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access Build Settings in Xcode 6?
提问by Dean
There seems to be a lot of variations of how to access the Build Settings variables (i.e. to define the base URL of a web service for different Debug
vs. Release
environments).
似乎有很多如何访问生成设置变量的变化(即定义不同的Web服务的基础URLDebug
与Release
环境)。
I created a User-Defined variable in Project -> Building Settings, one for each environment. Let's call it WEB_SERVICE_BASE_URL
.
我在 Project -> Building Settings 中创建了一个 User-Defined 变量,每个环境一个。让我们称之为WEB_SERVICE_BASE_URL
。
How do I access it in the code? I'm using XCode 6 and Swift.
如何在代码中访问它?我正在使用 XCode 6 和 Swift。
I've tried this but it doesn't work
我试过这个,但它不起作用
let api_key = ${WEB_SERVICE_BASE_URL}
I've also tried this and it also doesn't work
我也试过这个,它也不起作用
let api_key = NSUserDefaults.standardUserDefaults().stringForKey("WEB_SERVICE_BASE_URL")
Any suggestions? This seems to be a often needed solution, it's so easy in Rails, but not so in iOS development.
有什么建议?这似乎是一个经常需要的解决方案,它在 Rails 中很容易,但在 iOS 开发中则不然。
回答by Albert Bori
Here's how to set it up:
设置方法如下:
- Add a User-Defined setting to your target's
Build Settings
(which you did withWEB_SERVICE_BASE_URL
) - Add a new row to your target's
Info.plist
file with key:WEB_SERVICE_BASE_URL
, type:String
, value:${WEB_SERVICE_BASE_URL}
- 将用户定义的设置添加到您的目标
Build Settings
(您使用WEB_SERVICE_BASE_URL
) Info.plist
使用 key:WEB_SERVICE_BASE_URL
, type:String
, value:在目标文件中添加一个新行:${WEB_SERVICE_BASE_URL}
Here's how get the value:
以下是获取值的方法:
let api_key = Bundle.main.object(forInfoDictionaryKey: "WEB_SERVICE_BASE_URL") as? String
Note: These keys/values can be extracted from the package, so be sure to avoid storing sensitive data in there.
注意:这些键/值可以从包中提取,所以一定要避免在那里存储敏感数据。