Question

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?

Was it helpful?

Solution

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")

OTHER TIPS

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]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top