6

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

Rob
  • 415,655
  • 72
  • 787
  • 1,044
Mehmet Özcan
  • 103
  • 1
  • 1
  • 6

2 Answers2

20

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()
}
Austin Michael
  • 460
  • 4
  • 18
  • Hi Austin, print(json) result is { response = { success = 1; successmsg = "Successful Connection"; };} How can I get value of "success"? – Mehmet Özcan Feb 06 '20 at 08:26
  • Use this library to handle JSON, [https://github.com/SwiftyJSON/SwiftyJSON] – Austin Michael Feb 10 '20 at 10:12
  • 1
    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** – Fattie May 30 '22 at 13:42
1

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)
    }
}
DungeonDev
  • 1,176
  • 1
  • 12
  • 16