Search code examples
objective-cnsurlconnection

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

Try#2:

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

**O/P:

https://somesite.com/search/name?name=JOE

Any suggestions?


Solution

  • You can use NSURLComponents to build URLs:

    Objective-C:

    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.