6

I am trying to organize all my API url's in a single file, what I am doing is I created a header file and added the following lines

#define LOGIN_URL           @"http://192.168.100.100/api/login"
#define SIGNUP_URL          @"http://192.168.100.100/api/signup"
#define PRODUCTS_URL        @"http://192.168.100.100/api/products"
#define EMPLOYEE_URL        @"http://192.168.100.100/api/employee"
#define GET_PRODUCTS_URL    @"http://192.168.100.100/api/getproducts"
#define CLIENTS_URL         @"http://192.168.100.100/api/clients"

Here the base url is http://192.168.100.100/ which will keep on changing, I always have to find and replace the IP Address. Is there any better ways to organize API Url's?

icodebuster
  • 8,890
  • 7
  • 62
  • 65
  • Here's a similar question with good solutions. http://stackoverflow.com/questions/16448896/changing-base-url-depending-on-preprocessor-macro-value – VGruenhagen May 14 '13 at 19:17
  • See: [Build a list of constants variable from other constants](http://stackoverflow.com/q/10055187) – jscs May 14 '13 at 19:18

2 Answers2

13

Hey you may organise all your API Url's by using the following code

#define SITE_URL(url) @"http://192.168.100.100/api" url

#define LOGIN_URL           SITE_URL("/login")
#define SIGNUP_URL          SITE_URL("/signup")

#define PRODUCTS_URL        SITE_URL("/products")
#define EMPLOYEE_URL        SITE_URL("/employee")
#define GET_PRODUCTS_URL    SITE_URL("/getproducts")
#define CLIENTS_URL         SITE_URL("/clients")
icodebuster
  • 8,890
  • 7
  • 62
  • 65
  • 2
    I'd put it back the way it was. The IP address needs to be easily changed (for failover). Who cares if parts of the URL are similar? – Marcus Adams May 14 '13 at 19:25
  • @MarcusAdams my url has the word `api` so it does work for me. –  May 14 '13 at 19:29
6

I personally like to use constants over #define

Here is how I would do what you're trying to do.

MyAppConstants.h

extern NSString * const  kLOGIN_URL;  
extern NSString * const  kSIGNUP_URL; 
extern NSString * const  kPRODUCTS_URL;
extern NSString * const  kEMPLOYEE_URL;
extern NSString * const  kGET_PRODUCTS_URL;
extern NSString * const  kCLIENTS_URL;

MyAppConstants.m

NSString * const  kLOGIN_URL           = @"/login"
NSString * const  kSIGNUP_URL          = @"/signup"
NSString * const  kPRODUCTS_URL        = @"/products"
NSString * const  kEMPLOYEE_URL        = @"/employee"
NSString * const  kGET_PRODUCTS_URL    = @"/getproducts"
NSString * const  kCLIENTS_URL         = @"/clients"

Then when I use the constants I would do something like...

NSURL *loginURL = [NSURL URLWithString:[baseUrl stringByAppendingString:kLOGIN_URL]];
Chris Wagner
  • 20,773
  • 8
  • 74
  • 95