Is there any way to attach a NSDictionary of parameters to an NSURLRequest instead of manually making a string?

user2005643 picture user2005643 · Jan 23, 2014 · Viewed 20.7k times · Source

AFNetworking allows you to add an NSDictionary of parameters to a request, and it will append them to the request. So if I wanted to do a GET request with ?q=8&home=8888 I'd just making an NSDictionary like @{@"q": @"8", @"home": @"8888"} very simply.

Is there a way to do this with NSURLSession / NSURLConnection / NSURLRequest?

I know I can use NSJSONSerialization for appending JSON data, but what if I just want them as GET parameters in the URL? Should I just add a category?

Answer

Peter DeWeese picture Peter DeWeese · Sep 17, 2015

You can do this by updating the url using NSURLComponents and NSURLQueryItems. In the following example, assume that the URL parameter has already been set on an NSMutableURLRequest. You can modify it before using it to include each parameter from the NSDictionary params. Note that each parameter is encoded before it is written.

NSURLComponents *url = [[NSURLComponents alloc] initWithURL:request.URL resolvingAgainstBaseURL:YES];
NSMutableArray *queryItems = NSMutableArray.new;
[params enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) {
    [queryItems addObject:[NSURLQueryItem queryItemWithName:name
                           value:[value stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]]];
            }];
url.queryItems = queryItems;
request.URL = url.URL;