objective c - Where is an ideal location to store the root url in an iOS app to get access to an external API? -


where ideal location store root url in ios app access external api?

i'm thinking of using nsbundle not sure if right. or should using constant variable?

thanks in advance!

you have few options:

  1. create static class built interact api , keep url there.
  2. you can use constant variable defined in 1 of headers , import it
  3. you can use constant variable defined in prefix.pch (i don't recommend this)

when build production grade apps use 1st one. takes little bit longer, cleans code more. let's i'm interacting api has todo list on server somewhere. want request first todo list item each todo list item title , content.

i'll first create todo list class has 2 properties , 1 method:

    @property (nonatomic, strong) nsstring *title;     @property (nonatomic, strong) nsstring *content;     + (mytodolistitem*)todolistitemfromdictionary:(nsdictionary*)dict; 

all 1 method convert dictionary create in networking class json response todolist item.

now networking class have method definition like:

    + (void)getfirsttodolistitemwithcallback:(void(^)(mytodolistitem *item))callback; 

and implementation have of in it:

    static nsstring * const apirooturl = @"http://api.foo.com/v1/";     + (void)getfirsttodolistitemwithcallback:(void(^)(mytodolistitem *item))callback {         nsurl *url = [nsurl urlwithstring:urlstring];          //where use apirooturl         nsurlrequest *urlrequest = [nsurlrequest requestwithurl:[nsurl urlwithstring:[nsstring stringwithformat:@"%@%@", apirooturl, @"firsttodolistitem"]]];         nsoperationqueue *queue = [[nsoperationqueue alloc] init];         [nsurlconnection sendasynchronousrequest:urlrequest queue:queue completionhandler:^(nsurlresponse *response, nsdata *data, nserror *error) {             if (error) {                 nslog(@"error,%@", [error localizeddescription]);             } else {                 nsdictionary *dictionary = [nsjsonserialization jsonobjectwithdata:data options:kniloptions error:&error];                  //where magic happens never deal json anywhere else.                 callback([mytodolistitem todolistitemfromdictionary:dictionary]);             }          }];     } 

and finally, object:

    - (void)getmyfirstobjectsomewhereinsomeviewcontroller {         [mytodolistnetworker getfirsttodolistitemwithcallback:(void(^)(mytodolistitem *item))callback {             nslog(@"%@ %@", item.title, item.content);         }];     } 

Popular posts from this blog