Zhr Zhr - 5 months ago 43
Objective-C Question

Objective-C - Formatting GET request

What are the rules for passing the string parameter such as %JOHN% in a GET request url

my request url is supposed to look like: https://somesite.com/search/name?name=%SEARCH_KEYWORD%

Try#1: I did this

NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%%%@%%",SEARCH_KEYWORD]];

O/P: nil


NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%JOE%"]];



Any suggestions?


You can use NSURLComponents to build URLs:


NSURLComponents *components = [NSURLComponents componentsWithString:@"https://google.com"];
components.query = @"s=%search keywords%"

NSURL *url = components.URL;

Swift (careful with ! in production, I used to test in Playgrounds):

let components = NSURLComponents(string: "https://google.com")!
components = "s=%search keywords%"

let url = components!
print(url) // "https://google.com?s=%25search%20keywords%25"

Also if you need more complex queries NSURLComponent have a queryItems property.