Вы должны создать URLRequest
с заголовками и использовать dataTask
с этим запросом:
Вы можете установить параметры следующим образом:
url.queryItems = [
URLQueryItem(name: "parameterName", value: "parameterValue")
]
Вы можете установить httpMethod
let request = URLRequest(url: url)
request.httpMethod = "POST" // "POST", "GET", "PUT", "DELETE"
Добавление заголовков
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Вы можете установить jsonData
и использовать эти данные в запросе
let json = [
"key1": "value1",
"key2": "value2"
]
Словарь в формате JSON:
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
* 1032 USAGE *
let task = session.uploadTask(with: request, from: jsonData) { data, response, error in
// Do something...
}
task.resume()
БОНУС
/// Print response data
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print(dataString)
}
/// Print status code
if let httpResponse = response as? HTTPURLResponse {
print(httpResponse.statusCode)
}
Пример
let url = URLComponents(string: catURL)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
url.queryItems = [
URLQueryItem(name: "parameterName", value: "parameterValue")
]
let request = URLRequest(url: url)
request.allHTTPHeaderFields = ["application/json": "Content-Type"]
let task = session.dataTask(with: request) { ( data, response, error) in
if let taskHeader = response as? HTTPURLResponse {
print(taskHeader.statusCode)
}
if error != nil {
print("There is an error!!!")
print(error)
} else {
if let content = data {
do {
let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
if let items = dictionary["course"] as? [[String:Any]] {
for item in items {
if let ids = item["name"] {
print("iDS = \(ids)")
}