Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

ios - How to post the data in encoding structure?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need to create another string and then to data. This will be handled by Codable protocol and your JSONEncoder. You need to encode your post type using JSONEncoder and provide the data to the request.httpBody

Try this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...