2

How can I send a HTTP Get Request with the following parameters in Swift4 without using any external library?

URL: "https://api.newsapi.aylien.com/api/v1/stories"
Parameters = ["categories.confident": "true", "source.name" : "The New York Times", "cluster" : "false", "cluster.algorithm" : "lingo", "sort_by" : "published_at", "sort_direction" : "desc", "cursor" : "*", "per_page" : "10"]
Headers = ["X-AYLIEN-NewsAPI-Application-ID": "App-ID-Here", "X-AYLIEN-NewsAPI-Application-Key": "App-Key-Here"]
4
  • The same way you do in Swift 3. Use URLRequest and URLSession. Commented Oct 6, 2017 at 2:35
  • How do I add parameters and headers in a URLRequest? Commented Oct 6, 2017 at 2:36
  • 1
    This isn't a hard problem. You're asking how to do the most basic of functionality. Read the documentation. Commented Oct 6, 2017 at 2:43
  • Give it a try, and come back with a specific question. At the moment this question reads like a requirement that you want somebody to give you tho code for. Commented Oct 6, 2017 at 2:54

1 Answer 1

13

You can use like this :

let urlString = "https://api.newsapi.aylien.com/api/v1/stories"
let parameters = ["categories.confident": "true", "source.name" : "The New York Times", "cluster" : "false", "cluster.algorithm" : "lingo", "sort_by" : "published_at", "sort_direction" : "desc", "cursor" : "*", "per_page" : "10"]
let headers = ["X-AYLIEN-NewsAPI-Application-ID": "App-ID-Here", "X-AYLIEN-NewsAPI-Application-Key": "App-Key-Here"]

var urlComponents = URLComponents(string: urlString)

var queryItems = [URLQueryItem]()
for (key, value) in parameters {
    queryItems.append(URLQueryItem(name: key, value: value))
}

urlComponents?.queryItems = queryItems

var request = URLRequest(url: (urlComponents?.url)!)
request.httpMethod = "GET"

for (key, value) in headers {
    request.setValue(value, forHTTPHeaderField: key)
}

let task = URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in
    print(response)
}
task.resume()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.