How to organize an API URL in Objective-C

I am trying to organize my entire API url in a single file, what I do, 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 change, I always need to find and replace the IP address. Are there any more efficient ways to organize an Url API?

+6
source share
2 answers

Hey, you can organize your entire API URL 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") 
+13
source

I personally like to use constants over #define

This is how I will do what you are 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 constants, I would do something like ...

 NSURL *loginURL = [NSURL URLWithString:[baseUrl stringByAppendingString:kLOGIN_URL]]; 
+6
source

Source: https://habr.com/ru/post/945004/


All Articles