Alamofire POST Returning Data - swift

I am using Alamofire to make a post request to server. The post request is working fine.
Issue: When the post request is made, it returns some data which I need. How can I store/ retrieve that data
The POST Request:
Alamofire.request(.POST, postURL, parameters: params)

to get the response closure add
.response { request, response, data, error in }
to the end of your code
ie
Alamofire.request(.POST, "http://httpbin.org/get", parameters: ["foo": "bar"])
.response { request, response, data, error in
print(request)
print(response)
print(data)
print(error)
}

If you are using the latest version of AlamoFire.
If you are using the latest version of AlamoFire.
Try this working fine for me.(Change request arguments based on your need)
let url1 = "http://yoururl.com"
let head = [ "Accept": "application/json;charset=UTF-8",
"Content-Type": "application/json;charset=UTF-8"] // Adding headers
let p = ["Email":"anything","Password": "123"] // Adding parameters if any
Alamofire.request(.POST,url1, parameters: p, encoding : .JSON, headers : head)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
}

Related

Multiple Arguments in AlamoFire.Request

I am trying to access Spotify's web API. I am currently using Alamofire to request the search operation which only requires a token. However, I could not figure out why it won't let me send multiple arguments.
let headers = ["Authorization": "Bearer {your access token}"]
var searchURL = "https://api.spotify.com/v1/search?q=Odesza&type=track"
AF.request(.GET, url, headers: headers)
.responseJSON { response in
debugPrint(response)
}
Alamofire does a great job of formatting parameters to a request url. Just as you pass parameters with the .post method to the AF request function you also pass a parameters [string : any] to the AF request for .get methods as well. The difference is .post will put the parameters in the request.body/data vs. .get will format the parameters into the url with the ?q=my_search_string
something along the lines of this:
Let params: [string :any] = ["q": "odesza", "type":"track"]
AF.request(.GET, url, parameters:params, headers: headers) .responseJSON { response in debugPrint(response

Can't make post request using params as dictionary with Swift 4 & Alamofire

I'm trying to learn to call API with/without library. But the problem here confuses me.
I have params like this:
let parameters: [String:String] =
["key":"MY_KEY" ,
"q":sourceText,
"source": sourceLanguage),
"target": target)]
let headers: HTTPHeaders = [ "Content-type": "application/json"]
I make a post call like this:
Alamofire.request(urlString, method: HTTPMethod.post, parameters: parameters, headers: headers)
.responseJSON{ response in
guard response.result.error == nil else {
print("error calling POST on /todos/1")
print(response.result.error!)
return
}
// make sure we got some JSON since that's what we expect
guard let json = response.result.value as? [String: Any] else {
print("didn't get todo object as JSON from API")
print("Error: \(response.result.error)")
return
}
By this I get an error 403, saying that I do not have a valid API key (I tested the key with postman, and it is okay).
After many efforts, I have to change the code like this
let stringparams = "key=MY_KEY&q=\(sourceText)&source=\(sourceLanguage)&target=\(target)"
request.httpBody = stringparams.data(using: String.Encoding.utf8)
and using this: Alamofire.request(request)
it works!
I'm using Google Cloud Translation api. And the web use a REST api as said here: https://cloud.google.com/translate/docs/reference/translate
So why can't I use params as dictionary, but using the string (like formdata) will work here?
My guess is Alamofire didn't make the right BODY for the request from the parameters because other arguments is okay. But I don't know why.
And I think Google should accept a json params as they mentioned, in stead of using form data? I did try the original method, but it didn't work with JSON.
From what actually works for you it looks like you need to encode the parameters in the same style as a query. Try this:
struct ParameterQueryEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = parameters?
.map { "\($0)=\($1)" }
.joined(separator: "&")
.data(using: .utf8)
return request
}
}
You should then be able to perform the original call that you had before:
Alamofire.request(urlString,
method: HTTPMethod.post,
parameters: parameters,
encoding: ParameterQueryEncoding(),
headers: headers)
.responseJSON { response in
...
}
Try by using JSON encoding. Make sure you have removed ) from dictionary.
Alamofire.request(URL, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers)

POST request not working in swift3 with alamofire

I am using Alamofire for calling my API .
below is is the code.
func alamofirePost() {
let headers: HTTPHeaders = [ "content-type": "x-www-form-urlencoded"]
let todosEndpoint: String = "http://54.244.108.186:4000/api/post_upc"
let newTodo: [String: Any] = ["UPC": codeTextView.text, "DATE_TIME": currentTime() ]
print("i am in alamo")
Alamofire.request(todosEndpoint, method: .post, parameters: newTodo ,encoding: JSONEncoding.default,headers: headers )
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling POST on /todos/1")
print(response)
print(response.result.error!)
return
}
when i call the function , it is trying to inserting null values in the database
INSERT INTO `UPC`(`UPC`,`DATE_TIME`) VALUES (NULL,NULL)
Below is the response when i do in postman app.
can someone please help
Firstly in your Postman request you are POSTing your body as x-www-form-urlencoded but in your Swift example you are specifying that header as well. BUT you're actually submitting your POST body as a JSON payload. In contrast, your Postman request is a set of key/value pairs.
Additionally, the two keys appear to be named differently from your Swift example and your Postman example.
Swift uses UPC and DATE_TIME while Postman has upc_app and dttm_app so at a minimum you'll want to ensure you send along what your API expects

Extra Argument In A Call

I get the following error since I upgraded to Xcode 8:
Extra Argument In A Call
My code looks like this:
Alamofire.request(.GET, link).validate().responseJSON { response in
The error highlights link in red. It is defined further above the code:
let link = "http://www.gov.je/_layouts/15/C5.Gov.Je.CarParks/proxy.aspx"
Why do I get this error?
According to the document:
- Data Request - Simple with URL string
// Alamofire 3
Alamofire.request(.GET, urlString).response { request, response, data, error in
print(request)
print(response)
print(data)
print(error)
}
// Alamofire 4
Alamofire.request(urlString).response { response in // method defaults to `.get`
debugPrint(response)
}
So you need to remove .GET argument
let link = "http://www.gov.je/_layouts/15/C5.Gov.Je.CarParks/proxy.aspx"
Alamofire.request(link).responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}

How do I see Alamofire Request? [duplicate]

This question already has an answer here:
URL Encode Alamofire GET params with SwiftyJSON
(1 answer)
Closed 6 years ago.
I am trying to use Alamofire for an Api that has a Json body and a header requirement that needs Basic Authentication. When I test the call in Postman it works fine, however with AlamoFire I am getting a server error.
I am trying to see what the call is that's going out from Alamofire - but I can't seem to see it: (this is the code I am using)
edit:
Error is below
["errors": { }, "errorMessages": <__NSSingleObjectArrayI 0x6000000035c0>( Internal server error ) ]
Request is below
Alamofire.request(endpoint, method: .post, parameters: paramsEncoded, encoding: JSONEncoding.default, headers: headers)
.responseJSON(completionHandler: { (response) in
print(response.request) // This returns just the url eg "http://api.com
print(response.request?.httpBody) // This returns `Optional(85 bytes)`
})
I assume the request is not being created properly, but would be useful to understand what I should be seeing.
Edit: this line helped from the other question :
NSLog("Request: \(request!.httpMethod!) - \(request!.url!.absoluteString)\n\(request!.httpBody.map { body in String(data: body, encoding: .utf8) ?? "" } ?? "")")
Thanks to the question I have linked to as a duplicate for the help.
Print the whole request like this :
let request = Alamofire.request(endpoint, method: .post, parameters: paramsEncoded, encoding: JSONEncoding.default, headers: headers)
.responseJSON(completionHandler: { (response) in
print(response.request)
print(response.request?.httpBody)
})
print("REQUEST = \(request)")
I'm not sure you can get any more info than that though.
You need to add headers with your request.
let urlString = "https://httpbin.org/get"
let headers = ["Authorization": "123456"]
Alamofire.request(urlString, method: .post, parameters: ["foo": "bar"],encoding: JSONEncoding.default, headers: headers).responseJSON { response in
print(response.result.value)
}