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).
Asked
Active
Viewed 2.0k times
6
-
1show us what you have tried so far – Keshu R. Jan 31 '20 at 12:11
-
Use Alamofire... https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#using-alamofire – DungeonDev Jan 31 '20 at 12:13
-
[How to make an HTTP request in Swift?](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift) – Sangsom Jan 31 '20 at 12:21
2 Answers
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
-
1great 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