Swift 5, make http post request - swift

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

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

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

what is unsupported grant type error in swift?

I'm trying to make a simple login post request with URLSession with my userDetails object as input and request is of content type "application/x-www-form-urlencoded", in response i am supposed to get an object of "access token", "refresh token", "userdetails".
but i keep getting:
error = "unsupported_grant_type"
request on postman works but something is not right when I make a request in my project. what am i doing wrong here?? API team says the input object has to be correct which is exactly from the postman.
func loginUser() {
/// login request here
let url = URL(string: EndPoint.loginUser)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let userData: [String: Any] = [
"UserName": "myUserEmail",
"Password": "myPassword",
"grant_type": "password"
]
guard let httpBody = try? JSONSerialization.data(withJSONObject: userData, options: .prettyPrinted) else { return }
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, urlResponse, error) in
if let data = data {
do {
let jsonData = try JSONSerialization.jsonObject(with: data, options: [])
print(jsonData)
} catch let error {
debugPrint(error.localizedDescription)
}
}
}.resume()
}

Converting ecobee Alamofire request to use URLSession

As a followup to my last question (Alamofire syntax for ecobee request), I would prefer to just use URLSession for the request.
Now I'm back to a request that times out with status 408 using the following code:
guard let url = URL(string: "https://api.ecobee.com/1/thermostat") else { return }
let jsonParameters = [ "selection": [ "selectionType": "registered", "selectionMatch": "" ] ]
let jsonData = try! JSONEncoder().encode(jsonParameters)
let jsonString = String(decoding: jsonData, as: UTF8.self)
let queryParameters = ["format": "json", "body": jsonString]
let headers: HTTPHeaders = [.authorization(bearerToken: AUTH_TOKEN), .contentType("text/json")]
var request = try! URLRequest(url: url, method: .get, headers: headers)
request.httpBody = try! JSONEncoder().encode(queryParameters)
URLSession.shared.dataTask(with: request) { (data, resp, err) in
debugPrint(String(data: data!, encoding: .utf8)!)
}.resume()
I suspect I'm not adding the query parameters correctly.
I found my own solution using UrlComponents
func testRequest() {
guard var url = URLComponents(string: "https://api.ecobee.com/1/thermostat") else { return }
let jsonParameters = [ "selection": [ "selectionType": "registered", "selectionMatch": "" ] ]
let jsonData = try! JSONEncoder().encode(jsonParameters)
let jsonString = String(decoding: jsonData, as: UTF8.self)
let queryParameters = ["format": "json", "body": jsonString]
url.queryItems = queryParameters.map { URLQueryItem(name: $0.key, value: $0.value) }
let headers = [
"Authorization": "Bearer \(core.accessToken)",
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
]
var request = URLRequest(url: url.url!)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
URLSession.shared.dataTask(with: request) { (data, resp, err) in
debugPrint(String(data: data!, encoding: .utf8)!)
}.resume()
}

urlrequest not sending post request

Hi i am new to IOS App developement.
My code is
func sendRequest<T: Decodable>(api: String, parameters: [String: String]? = nil, outputBlock: #escaping (T) -> () ) {
guard let url = URL(string: "http://xxyyzz.com/appRegister.php") else {return}
print("hitting : -", url.absoluteString)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let newparam = ["name": "rr", "pass": "123456", "email": "rr#rr.com", "passConfirm":"123456"]
let httpBody = try? JSONSerialization.data(withJSONObject: newparam)
request.httpBody = httpBody
if let data = request.httpBody, let str = String(data: data, encoding: String.Encoding.utf8) {
print(str)
}
URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
DispatchQueue.main.async {
Indicator.shared.hideProgressView()
if let err = error {
print(err.localizedDescription)
return
}
guard let data = data else {return}
do {
let obj = String(data: data, encoding: String.Encoding.utf8)
print(obj ?? "oberrrrr")
}
}
}.resume()
}
and console printed result as per code is below
hitting : - http://xxyyzz.com/appRegister.php
{"email":"rr#rr.com","passConfirm":"123456","name":"rr","pass":"123456"}
{"error":"Please enter all fields."}
url and parameters works well on postman that means their is something missing in my code.
just to answer the problem if anyone else faces this.
this code is fine but the problem was with php web-service as the backend developer was not accepting json values as parameter instead form data was need to send.
So, two types of fix can be made here
accept json at backend by adding :-
$postdata = file_get_contents("php://input");
$request = json_decode($postdata, true);
send form data instead json
func sendRequest<T: Decodable>(api: String, parameters: [String: Any]? = nil, outputBlock: #escaping (T) -> () ) {
guard let url = URL(string: api) else {return}
print("hitting : -", url.absoluteString)
var request = URLRequest(url: url)
if let parameters = parameters {
request.httpMethod = "POST"
var postArr = [String]()
for(key, value) in parameters
{
postArr.append(key + "=\(value)")
}
let postString = postArr.map { String($0) }.joined(separator: "&")
request.httpBody = postString.data(using: .utf8)
if let data = request.httpBody, let str = String(data: data, encoding: String.Encoding.utf8) {
print(str)
}
}
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
Indicator.shared.hideProgressView()
if let err = error {
print(err.localizedDescription)
return
}
guard let data = data else {return}
do {
let obj = try JSONDecoder().decode(T.self, from: data)
outputBlock(obj)
} catch let jsonErr {
print(jsonErr)
}
}
}.resume()
}

Send dictionary data via HTTP POST method in Swift

I'm trying to make an HTTP post request with params set in a dictionary here's my dict
let parameters = [
["name": "tag","value": "login"],
["name": "email","value": "s#s.com"],
["name": "password","value": "aaaa"]
]
but I don't to know how to access it in hers's my complete request function
func data_request(_ url:String)
{
let parameter = [
["name": "tag","value": "login"],
["name": "email","value": "s#s.com"],
["name": "password","value": "aaaa"]
]
let url:NSURL = NSURL(string: url)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
let paramString = parameter?
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
print("error")
return
}
if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
{
print(dataString)
}
}
task.resume()
}
Need to convert dictionary to json string like below:
let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
After that pass to the http.Body
// insert json data to the request
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
print("Result -> \(result)")
} catch {
print("Error -> \(error)")
}
}
task.resume()
return task
} catch {
print(error)
}
You need to convert the Dictionary into Data and set it to httpBody
you could solve in this way
let paramData = try? JSONSerialization.data(withJSONObject: parameter, options: [])
request.httpBody = paramData

NSData is nil After AsynchronousRequest In Swift

I am trying to add video data to the HTTP Request's body but sometimes video data is turning to nil but sometimes not. Is there anything to fix this situation? When I delete the app from my app and after doing simulation again, nothing happened.
#IBAction func post(sender: AnyObject) {
let videodata = NSData(contentsOfURL: videoURL!)
let headers = [
"authorization": "Token \(userToken!)",
"content-type": "/*/",
"content-disposition": "attachment;filename=deneme.mp4",
"cache-control": "no-cache"
]
let request = NSMutableURLRequest(URL: NSURL(string: "http://molocate.elasticbeanstalk.com/video/upload/")!,
cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData,
timeoutInterval: 10.0)
request.HTTPMethod = "POST"
request.allHTTPHeaderFields = headers
request.HTTPBody = videodata
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
//print(NSString(data: data!, encoding: NSUTF8StringEncoding))
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
print("Result -> \(result)")
let statue = result["result"] as! String
if(statue == "success"){
let videoId = result["video_id"] as! String
let videoUrl = result["video_url"] as! String
print(videoUrl)
let json = [
"video_id": videoId,
"video_url": videoUrl,
"caption": "This city is awesome:)",
"category": "travel",
"tagged_users": [["username": "amertturker"]],
"location": [
[
"id": "mekmaekfmaıhjagej3ıo45j3kt348t3gkg",
"latitude": "35.342643",
"longitude": "32.345236",
"name": "Milas Merkez Kafasına göre herkes",
"address": "Milas aq"
]
]
]
let newheaders = [
"authorization": "Token \(userToken!)",
"content-type": "application/json",
"cache-control": "no-cache"
]
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
print(NSString(data: jsonData, encoding: NSUTF8StringEncoding))
// create post request
let url = NSURL(string: "http://molocate.elasticbeanstalk.com/video/update/")!
let request = NSMutableURLRequest(URL: NSURL(string: "http://molocate.elasticbeanstalk.com/video/update/")!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)
request.HTTPMethod = "POST"
request.allHTTPHeaderFields = newheaders
request.HTTPBody = jsonData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
print(response)
//print(NSString(data: data!, encoding: NSUTF8StringEncoding))
dispatch_async(dispatch_get_main_queue(), {
if error != nil{
print("Error -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
print("Result -> \(result)")
} catch {
print("Error -> \(error)")
}
})
}
task.resume()
} catch {
print(error)
}
} else{
// self.displayAlert("Hata", message: result["result"] as! String)
// UIApplication.sharedApplication().endIgnoringInteractionEvents()
// self.activityIndicator.stopAnimating()
// self.activityIndicator.hidesWhenStopped = true
}
} catch {
print("Error -> \(error)")
}
}
})
dataTask.resume()
do {
try NSFileManager.defaultManager().removeItemAtPath(videoPath!) //.removeItemAtURL(fakeoutputFileURL!)
dispatch_async(dispatch_get_main_queue()) {
print("siiiiil")
self.performSegueWithIdentifier("finishUpdate", sender: self)
}
} catch _ {
}
Your calling the httprequest asynchronously and then trying to use the data on the calling thread. It hasn't been populated until after the http request has returned which will occur at an undetermined future time. Anything you want to do with videoData should be done inside the completion handler, otherwise you are in a race condition and it might be nil when you call it.