Swift 5, make http post request

13,910

Solution 1

Below is the code for Post Method,using URLSession

let Url = String(format: "http://10.10.10.53:8080/sahambl/rest/sahamblsrv/userlogin")
    guard let serviceUrl = URL(string: Url) else { return }
    let parameters: [String: Any] = [
        "request": [
                "xusercode" : "YOUR USERCODE HERE",
                "xpassword": "YOUR PASSWORD HERE"
        ]
    ]
    var request = URLRequest(url: serviceUrl)
    request.httpMethod = "POST"
    request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
        return
    }
    request.httpBody = httpBody
    request.timeoutInterval = 20
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print(error)
            }
        }
    }.resume()
}

Solution 2

Try this with Alamofire 4.x

let parameters: [String: Any] = [
    "request": [
            "xusercode" : "YOUR USERCODE HERE",
            "xpassword": "YOUR PASSWORD HERE"
    ]
]

Alamofire.request("YOUR URL HERE", method: .post, parameters: parameters,encoding: JSONEncoding.default, headers: nil).responseJSON {
    response in
    switch response.result {
    case .success:             
    print(response)
        break
    case .failure(let error):
        print(error)
    }
}
Share:
13,910

Related videos on Youtube

Mehmet Özcan
Author by

Mehmet Özcan

Updated on June 04, 2022

Comments

  • Mehmet Özcan
    Mehmet Özcan almost 2 years

    Postman

    How can I do attached "postman operation" on Swift 5? i would like to use this code for login with rest service on ios(iphone).

  • Mehmet Özcan
    Mehmet Özcan over 4 years
    Hi Austin, print(json) result is { response = { success = 1; successmsg = "Successful Connection"; };} How can I get value of "success"?
  • Austin Michael
    Austin Michael about 4 years
    Use this library to handle JSON, [github.com/SwiftyJSON/SwiftyJSON]
  • Fattie
    Fattie almost 2 years
    great answer but it's an incredibly bad idea to use any library for json nowadays in iOS. it is absolutely built in to Swift/iOS and is trivial to use