Where to set environmental variables in iOS?

后端 未结 3 2051
旧巷少年郎
旧巷少年郎 2020-12-28 11:02

In my development I wish to hit a development URL when im testing but when the app is run on my iPhone, I want it to run on production URL. How do I get about setting this i

相关标签:
3条回答
  • 2020-12-28 11:23

    I prefer the #define method as well. For those less familiar, those are pre-processor directives and are set even before the compiler gets hold of the code.

    Environment variables are set at runtime of the program, and can be manipulated in the scheme editor of Xcode 4.x+. You could set up different schemes to hit different testing environments.

    To access an environment variable at runtime from within your code, use the following:

    NSString *url = @"http://standardurl.com";
    NSDictionary *env = [[NSProcessInfo processInfo] environment];
    NSString *overrideURL = [env valueForKey:@"url"];
    if (overrideURL != nil)
      url = overrideURL;
    
    0 讨论(0)
  • 2020-12-28 11:24

    You can also set the different URLs in your plist file by adding new String rows if you don't want to use a constants file.

    (Not much to be gained here though I admit but depends on where you prefer to set up your urls)

    In your myApp-plist file add new rows like this:

    "DevelopmentEndpoint" "String" "http://development.endpoint.com"

    "ProductionEndpoint" "String" "http://production.endpoint.com"

    In your code:

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

    In your build settings add DEVELOPMENT under the "Preprocessor Macros" section for Debug or Release etc.

    0 讨论(0)
  • 2020-12-28 11:41

    There are lots of ways to do this. My preferred method is to create a file called Constants.h that looks like this:

    //
    //  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
    

    Then, I just include it in my *-Prefix.pch file like this:

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

    In your build settings, set DEVELOPMENT, or STAGING, or PRODUCTION = 1.

    Now you can access things like ROOT_URL anywhere in your project.

    Good luck!

    0 讨论(0)
提交回复
热议问题