在iOS中设置环境variables的地方?

在我的开发中,我希望在testing时创build一个开发URL,但是当我的iPhone运行该应用程序时,我希望它在生产URL上运行。 我如何得到有关在Xcode中设置?

几乎看起来像我需要能够设置环境variables(在这种情况下是不同的url)。

我在哪里设置? 请相信我,因为我是相当新的

谢谢

有很多方法可以做到这一点。 我最喜欢的方法是创build一个名为Constants.h的文件,如下所示:

// // Constants.h // #ifndef Constants_h #define Constants_h #pragma mark - Instances #ifdef DEVELOPMENT #define ROOT_URL @"http://127.0.0.1:8000" #endif #ifdef STAGING #define ROOT_URL @"http://staging.example.com" #endif #ifdef PRODUCTION #define ROOT_URL @"http://production.example.com" #endif 

然后,我只是将其包含在我的* -Prefix.pch文件中,如下所示:

 #ifdef __OBJC__ #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> #import "Constants.h" #endif 

在您的构build设置中,设置“开发”或“展开”或“生产= 1”。

现在,您可以在项目的任何位置访问ROOT_URL等内容。

祝你好运!

我更喜欢#define方法。 对于那些不太熟悉的,那些是预处理器指令,甚至在编译器掌握代码之前就已经设置好了。

Environment variables是在程序运行时设置的,可以在Xcode 4.x +的scheme editor中进行操作。 您可以设置不同的scheme来打不同的testing环境。

要在代码中在运行时访问环境variables,请使用以下命令:

 NSString *url = @"http://standardurl.com"; NSDictionary *env = [[NSProcessInfo processInfo] environment]; NSString *overrideURL = [env valueForKey:@"url"]; if (overrideURL != nil) url = overrideURL; 

如果您不想使用常量文件,也可以通过添加新的String行来在plist文件中设置不同的URL。

(虽然我承认这里没有多less东西,但取决于你喜欢在哪里设置你的url)

在你的myApp-plist文件中添加这样的新行:

“DevelopmentEndpoint”“String”“http://development.endpoint.com&#x201D;

“ProductionEndpoint”“String”“http://production.endpoint.com&#x201D;

在你的代码中:

 // Get endpoint from main bundle #ifdef DEVELOPMENT NSString *endpoint = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"DevelopmentEndpoint"]; #else NSString *endpoint = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"ProductionEndpoint"]; #endif 

在您的构build设置中,在“预处理器macros”部分中为debugging或发布等添加开发。