NSURLSession send parameters with get

GET data needs to be part of the url's query string. Some methods will accept a dictionary of parameters for POST/PUT requests, but these methods will not add the dictionary to the url for you if you're using the GET method.

If you'd like to keep your GET parameters in a Dictionary for cleanliness or consistency, consider adding a method like the following to your project:

func buildQueryString(fromDictionary parameters: [String:String]) -> String {
    var urlVars:[String] = []
    
    for (k, value) in parameters {
        let value = value as NSString
        if let encodedValue = value.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) {
            urlVars.append(k + "=" + encodedValue)
        }
    }

    return urlVars.isEmpty ? "" : "?" + urlVars.joined(separator: "&")
}

This method will take a dictionary of key/value pairs and return a string you can append to your url.

For example, if your API requests allow for multiple request methods (GET/POST/etc.) you'll only want to append this query string to your base api url for GET requests:

if (request.HTTPMethod == "GET") {
    urlPath += buildQueryString(fromDictionary: parm)
}

If you're only making GET requests, there's no need to check for which method you'll be using to send your data.


Bit crazy that none of the answers here suggest using NSURLComponents and NSURLQueryItem objects. That is the safest and most modern way to do this.

var iTunesSearchURL = URLComponents(string: "https://itunes.apple.com/search")!
iTunesSearchURL.queryItems = [URLQueryItem(name: "term", value: trackName),
                              URLQueryItem(name: "entity", value: "song"),
                              URLQueryItem(name: "limit", value: "1")]

let finalURL = iTunesSearchURL.url

@paul-mengelt's answer in Objective C:

-(NSString *) buildQueryStringFromDictionary:(NSDictionary *)parameters {
    NSString *urlVars = nil;
    for (NSString *key in parameters) {
        NSString *value = parameters[key];
        value = [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
        urlVars = [NSString stringWithFormat:@"%@%@=%@", urlVars ? @"&": @"", key, value];
    }
    return [NSString stringWithFormat:@"%@%@", urlVars ? @"?" : @"", urlVars ? urlVars : @""];
}