I am using two models GET and POST which are encodable and decodable
using the below code i am able to get the data in GET model, but i am not able to post the data with POST model.
please guide me how to post the data using POST model
let url = URL(string: "<YOUR URL HERE>")
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
"Accept" : "application/json",
"Content-Type" : "application/x-www-form-urlencoded"
]
let session = URLSession(configuration: config)
var request = URLRequest(url: url!)
request.encodeParameters(parameters: ["username": username, "password":
password])
let task = session.dataTask(with: request) { data, response, error in
guard let data = data else { return }
do {
let sentPost = try JSONDecoder().decode(Get.self, from: data)
print(sentPost)
} catch {}
}
task.resume()
model
struct Post: Encodable, Decodable {
let username: String
let password: String
}
extension for URLRequest
extension URLRequest {
private func percentEscapeString(_ string: String) -> String {
var characterSet = CharacterSet.alphanumerics
characterSet.insert(charactersIn: "-._* ")
return string
.addingPercentEncoding(withAllowedCharacters: characterSet)!
.replacingOccurrences(of: " ", with: "+")
.replacingOccurrences(of: " ", with: "+", options: [], range: nil)
}
mutating func encodeParameters(parameters: [String : String]) {
httpMethod = "POST"
let parameterArray = parameters.map { (arg) -> String in
let (key, value) = arg
return "(key)=(self.percentEscapeString(value))"
}
httpBody = parameterArray.joined(separator: "&").data(using: String.Encoding.utf8)
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…