在Swift4中添加HTTP标头和参数

时间:2017-10-06 02:33:38

标签: ios swift4

如何在不使用任何外部库的情况下在Swift4中使用以下参数发送HTTP Get Request?

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"]

1 个答案:

答案 0 :(得分:7)

您可以这样使用:

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()