如何在编码结构中发布数据?

时间:2018-05-21 08:03:19

标签: ios swift

我正在使用两个可编码和可解码的GET和POST模型

使用下面的代码,我能够在GET模型中获取数据,但我无法使用POST模型发布数据。

请指导我如何使用POST模型发布数据

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

模型

struct Post: Encodable, Decodable {
    let username: String
    let password: String
}

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

1 个答案:

答案 0 :(得分:1)

您不需要创建另一个字符串,然后再创建数据。这将由Codable协议和您的JSONEncoder处理。您需要使用JSONEncoder对帖子类型进行编码,并将数据提供给request.httpBody

试试这个:

let url = URL(string: "<YOUR URL HERE>")
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
    "Accept" : "application/json",
    "Content-Type" : "application/x-www-form-urlencoded"
]

do {
    let aPost = Post(username: "username", password: "password")
    let encoder = JSONEncoder()
    let encodedPost = try encoder.encode(aPost)

    let session = URLSession(configuration: config)
    var request = URLRequest(url: url!)
    request.httpMethod = "POST"
    request.httpBody = encodedPost

    let task = session.dataTask(with: request) { data, response, error in
        do {
            let sentPost = try JSONDecoder().decode(Get.self, from: data)
            print(sentPost)
        } catch { 
            print(error.localizedDescription)
        }
    }
    task.resume()
} catch {
    print(error.localizedDescription)
}