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)
}
}
Related videos on Youtube
Author by
Mehmet Özcan
Updated on June 04, 2022Comments
-
Mehmet Özcan almost 2 years
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).
-
iOSArchitect.com over 4 yearsshow us what you have tried so far
-
DungeonDev over 4 yearsUse Alamofire... github.com/Alamofire/Alamofire/blob/master/Documentation/…
-
Sangsom over 4 years
-
-
Mehmet Özcan over 4 yearsHi Austin, print(json) result is { response = { success = 1; successmsg = "Successful Connection"; };} How can I get value of "success"?
-
Austin Michael about 4 yearsUse this library to handle JSON, [github.com/SwiftyJSON/SwiftyJSON]
-
Fattie almost 2 yearsgreat 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