olacak dataTaskWithURL
'dan. Yani, Swift 2'de sen request.HTTPBody
o JSON olarak ayarlanır ve bir POST isteği olduğunu belirtebilirsiniz:
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
request.HTTPMethod = "POST"
request.updateBasicAuthForUser("test", password: "password1")
let dictionary = ["email": usr, "userPwd": pwdCode]
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: [])
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard let data = data where error == nil else {
print(error) // some fundamental network error
return
}
do {
let responseObject = try NSJSONSerialization.JSONObjectWithData(data, options: [])
print(responseObject)
} catch let jsonError {
print(jsonError)
print(String(data: data, encoding: NSUTF8StringEncoding)) // often the `data` contains informative description of the nature of the error, so let's look at that, too
}
}
task.resume()
Swift 3'te eşdeğer kodudur:
var request = URLRequest(url: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
request.httpMethod = "POST"
let dictionary = ["email": usr, "userPwd": pwdCode]
request.httpBody = try! JSONSerialization.data(withJSONObject: dictionary)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error) // some fundamental network error
return
}
do {
let responseObject = try JSONSerialization.jsonObject(with: data)
print(responseObject)
} catch let jsonError {
print(jsonError)
print(String(data: data, encoding: .utf8)) // often the `data` contains informative description of the nature of the error, so let's look at that, too
}
}
task.resume()
teşekkürler Rob ... Ben şimdi yapıyorum .. –
Merhaba Rob, sana çok teşekkür ederim ... bu benim sorunumu çözdü. –
@Rob, NSJSonSerialization ile benzer bir şey var mı, ancak "application-javascript" içerik türü için biliyor musunuz? –