swiftapiquery-stringurlrequest

How to pass an argument (args) to a `request.get`?


I'm trying to find out how to pass an argument (args) to a request.get. I know how to pass a token to the HTTP header like this:

request.httpMethod = "GET"
request.setValue(token, forHTTPHeaderField: "token")

But if I was going to pass the email as args to the request, how do I do that?

GET https://myapi/check_email?email=user1@gmail.com


Solution

  • That actually belongs to the URL and it has nothing to do with the HTTP method. So you need to add a query item to the url:

    let theURL = URL(string: "https://myapi/check_email")!
    var urlComponents = URLComponents(url: theURL, resolvingAgainstBaseURL: true)!
    let queryItem = URLQueryItem(name: "email", value: "user1@gmail.com")
    urlComponents.queryItems = [queryItem]
    let newURL = urlComponents.url!
    

    This works on any HTTP method (including GET POST, PUT, etc.).