Question

in my app, I'm currently sending http requests from each viewcontroller. However, currently I'm implementing one class, that is supposed to have method for sending requests.

My requests vary in number of parameters. For example, to get list of things for tableview I need to put category, subcategory, filter and 5 more parameters into request.

This is what my request looks like now:

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
         [request setValue:verifString forHTTPHeaderField:@"Authorization"]; 
         [request setURL:[NSURL URLWithString:@"http://myweb.com/api/things/list"]];
         [request setHTTPMethod:@"POST"];
         [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

         NSMutableString *bodyparams = [NSMutableString stringWithFormat:@"sort=popularity"];
         [bodyparams appendFormat:@"&filter=%@",active];
         [bodyparams appendFormat:@"&category=%@",useful];
         NSData *myRequestData = [NSData dataWithBytes:[bodyparams UTF8String] length:[bodyparams length]];
[request setHTTPBody:myRequestData]

My first idea was to create method, that accepts all of these parameters, and those, which are not needed would be nil, then I would test which are nil and those which are not nil would be appended to parameter string (ms).

This is however pretty inefficient. Later on I was thinking about passing some dictionary with stored values for a parameter. Something like array list with nameValuePair that's used in android's java.

I'm not sure, how would I get keys and objects from my dictionary

    -(NSDictionary *)sendRequest:(NSString *)funcName paramList:(NSDictionary *)params 
{
  // now I need to add parameters from NSDict params somehow
  // ?? confused here :)   
}
Was it helpful?

Solution

You could construct your params string from a dictionary with something like this:

/* Suppose that we got a dictionary with 
   param/value pairs */
NSDictionary *params = @{
    @"sort":@"something",
    @"filter":@"aFilter",
    @"category":@"aCategory"
};

/* We iterate the dictionary now
   and append each pair to an array
   formatted like <KEY>=<VALUE> */      
NSMutableArray *pairs = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in params) {
    [pairs addObject:[NSString stringWithFormat:@"%@=%@", key, params[key]]];
}
/* We finally join the pairs of our array
   using the '&' */
NSString *requestParams = [pairs componentsJoinedByString:@"&"];

If you log the requestParams string you will get:

filter=aFilter&category=aCategory&sort=something

PS I totally agree with @rckoenes that AFNetworking is the best solution for this kind of operations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top