Most of the models in my iOS app query a web server. I would like to have a configuration file storing the base URL of the server. It will look something like this:
#define BASEURl @"http://myWebService.appspot.com/xyz/xx"
then anywhere in project to use BASEURL:
NSString *LOGIN_URL= [BASEURl stringByAppendingString:@"/users/login"];
Updated: In Xcode 6 you will not find default .pch file created in your project. So please use PCH File in Xcode 6 to insert .pch file in your project.
Updates: For SWIFT
& Right away declare / define member
Example:
var STATUS_BAR_GREEN : UIColor = UIColor(red: 106/255.0, green: 161/255.0, blue: 7/255.0, alpha: 1) //
You could also do a
#define kBaseURL @"http://192.168.0.123/"
in a "constants" header file, say constants.h
. Then do
#include "constants.h"
at the top of every file where you need this constant.
This way, you can switch between servers depending on compiler flags, as in:
#ifdef DEBUG
#define kBaseURL @"http://192.168.0.123/"
#else
#define kBaseURL @"http://myproductionserver.com/"
#endif
The way I define global constants:
AppConstants.h
extern NSString* const kAppBaseURL;
AppConstants.m
#import "AppConstants.h"
#ifdef DEBUG
NSString* const kAppBaseURL = @"http://192.168.0.123/";
#else
NSString* const kAppBaseURL = @"http://website.com/";
#endif
Then in your {$APP}-Prefix.pch file:
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "AppConstants.h"
#endif
If you experience any problems, first make sure that you have the Precompile Prefix Header option set to NO.
I do think that another way to do this is far simpler and you will just include it in files you need them included in, not ALL the files, like with the .pch prefix file:
#ifndef Constants_h
#define Constants_h
//Some constants
static int const ZERO = 0;
static int const ONE = 1;
static int const TWO = 2;
#endif /* Constants_h */
After that you include this header file in the header file that you want. You include it in header file for the specific class that you want it included in:
#include "Constants.h"
For a number you can use it like
#define MAX_HEIGHT 12.5
I'd use a configuration object that initializes from a plist
.
Why bother other classes with irrelevant external stuff?
I created eppz!settigns soley for this reason. See article Advanced yet simple way to save to NSUserDefaults for incorporating default values from a plist
.