0

I'm almost certain that I recently saw an networking related method that allowed setting of URL parameters with an NSDictionary.

It was part of the new NSURLSession classes but I can't find it.

Essentially, instead of doing the url like...

@"www.blah.com/something.php?value=18&name=hello"

You could do...

theRequest.parameters = @{@"value":@18, @"name":@"hello"};

Am I imagining this or does this exist?

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • 1
    Check out this [link](http://stackoverflow.com/questions/21299362/is-there-any-way-to-attach-a-nsdictionary-of-parameters-to-an-nsurlrequest-inste?answertab=active#tab-top) – Greg Mar 06 '14 at 17:27
  • 1
    If it doesn't exist, why not write it? :) – matt Mar 06 '14 at 17:28
  • 1
    [AFNetworking](https://github.com/AFNetworking/AFNetworking) uses this pattern quite a bit. `NSURLSession` methods, themselves, don't take dictionaries as parameters to requests, but it's not hard to write the code to convert the dictionary into JSON or `application/x-www-form-urlencoded` requests. But AFNetworking generally makes you life easier. – Rob Mar 06 '14 at 17:32
  • @Rob I have been thinking about using AFNetworking. I don't know if it's actually needed though. I'm starting a completely fresh project so I'll have a look at it. – Fogmeister Mar 06 '14 at 17:34

1 Answers1

2

Why not write it your self? you can use that, just keep the right order when you put the values into the dictionary.

- (NSString *)makeURLFromDictionary:(NSString *)url values:(NSDictionary *)dictionary
  {
NSMutableString *string = [[NSMutableString alloc]initWithString:url];
[string appendString:@"?"];
for (id key in dictionary) {
    [string appendString:key];
    [string appendString:@"="];
    [string appendString:[dictionary objectForKey:key]];
    [string appendString:@"&"];
}
//this will remove the last &
[string deleteCharactersInRange:NSMakeRange([string length]-1, 1)];

return string;
}

Please just check the returned string, if I'm not wrong you should put it in reverse way, F.I.L.O(First in Last Out style).

enter the dict's values like this:

NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:@"hello" forKey:@"name"];
[dict setObject:@"18" forKey:@"value"];

NSString *urlString = [self makeURLFromDictionary:@"www.blah.com/somthing.php" values:dict];

Hop i help you.

Dekel Maman
  • 2,077
  • 1
  • 15
  • 16
  • 1
    +1 BTW, make sure you call `CFURLCreateStringByAddingPercentEscapes` on the value you add after the `=` (as illustrated in the latter part of [this answer](http://stackoverflow.com/a/21079176/1271826)). – Rob Mar 06 '14 at 18:46