response.result.value in alamofire post method is nil - ios

let parametersDictionary = [
"email" : "name#gmail.com",
"password" : "password"
]
Alamofire.request("http://nanosoftech.com/store/user_check", method: .post, parameters: (parametersDictionary as NSDictionary) as? Parameters , encoding: JSONEncoding.default, headers: nil).responseJSON { response in
print("response:", response.result.value)
}
I'm working in post method api and above code is not working. I'm getting nil response. But this url is working properly in postman and android studio too. What is the reason behind this issue?

Your url only works when requesting using form with url encoded
Try to use this, as documented on GitHub
Alamofire.request("http://nanosoftech.com/store/user_check", method: .post, parameters: parametersDictionary , encoding: URLEncoding.default)
If this encoding doesn't work, try encoding: URLEncoding.httpBody

Just write look Like bellow.. It is working for me
Alamofire.request("http://era.com.bd/UserSignInSV", method: .post,parameters:["uname":txtUserId.text!,"pass":txtPassword.text!]).responseJSON{(responseData) -> Void in
if((responseData.result.value != nil)){
let jsonData = JSON(responseData.result.value)
}
}

Related

Alamofire 4 missing parameters in POST

Spent hours on this with no success.
I'm using Alamofire to make a HTTP POST to back end server which requires some parameters to be supplied with request.
I'm successfully hitting the server but the server is responding with a 500 stating no parameters were sent?
I've tried most of the SO solutions (changing the encoding type, setting parameters as NSDict, etc) but with no success.
Any help greatly appreciated.
PS its Swift3 with Alamofire 4
Code:
let params: [String: String] = ["deviceID": "Some device ID",
"email": "email","password": "password","userid": "1234",
"username":"gordon"]
let request_params: Parameters = ["LoginUser" : params]
let url = "https://myserver/LogIn" as String
Alamofire.request(url, method: .post, parameters: request_params, encoding: URLEncoding.default, headers: [
"Content-Type": "application/x-www-form-urlencoded"
]).responseString { (response:DataResponse<String>) in
switch(response.result) {
case.success(let data):
print("success",data)
print(response.response)
case.failure(let error):
print("Failed!",error)
}
}
Update:
Below is the body of the POST, it looks like this is where the problem exists:
Alamofire POST body (from above code) -
(LoginUser%5BdeviceID%5D=12345&LoginUser%5Bemail%5D=gordon%40test.com&LoginUser%5Buserid%5D=00000000-0000-0000-0000-000000000000&LoginUser%5Bpassword%5D=testPassword&LoginUser%5Busername%5D=gordon)
It should be something like (ignoring the encoding values):
This is a functional post body-
LoginUser=%7B%22deviceID%22%3A%22%22%2C%22email%22%3A%22gordon%40test.com%22%2C%22password%22%3A%22testPassword%22%2C%22userid%22%3A%2200000000-0000-0000-0000-000000000000%22%2C%22username%22%3A%22gordon%22%7D
As you can see the Alamofire post seems to concatenate the LoginUser to start of each attribute? Also missing the LoginUser= at start??
Try to use JSONEncoding.default instead of URLEncoding.default
OK so I got this working with the below code, would be very interested in understanding if this is the most efficient means of posting param?
let params: NSMutableDictionary? = ["deviceID": "someDeviceID",
"email": "emailAddress","password": "aSecret","userid": "12345",
"username":"gordon"]
let url = "https://serverAdrress" as String
let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)
let json: NSString! = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
let request_params: Parameters = ["LoginUser" : json as Any]
Alamofire.request(url, method: .post, parameters: request_params, encoding: URLEncoding.httpBody, headers: [
"Content-Type": "application/x-www-form-urlencoded"
]).responseString { (response:DataResponse<String>) in
switch(response.result) {
case.success(let data):
print("success",data)
print(NSString(data: (response.request?.httpBody)!, encoding: String.Encoding.utf8.rawValue))
print(response.response)
case.failure(let error):
print("Not Success",error)
}
}

Alamofire server requests converts integer parameters to string

I have to send request having fields such as
id:1
Issue is that when I check apache logs I see that field is in form of
id:"1"
That is rather than having Integer 1 , I am getting String "1". Here is my code
let parameters: Parameters = [
"viewModel":viewModel];
let headers: HTTPHeaders = [
"Authorization": "Bearer " + getToken(),
"Accept": "application/json"
]
Alamofire.request(setUrl(),method:.post,parameters:parameters,headers: headers).responseJSON{
response in
print("Response:\(String(describing:response.result.value))")
switch response.result {
case .success:
self.status = true;
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
self.responseString = utf8Text
}
self.responseJSON = JSON(response.result.value as Any)
case .failure:
self.status = false;
}
completed()
}
Before request is initiated , i have made sure that all required fields are in Integer. Other fields are string , hence I am using Dictionary of Type [String:Any]
What am I doing wrong? I need to make sure that integer fields remain integer.
Setting encoding to
JSONEncoding.default
worked perfectly for me.
The request can also be like
Alamofire.request(url, method: .post, parameters: object, encoding: JSONEncoding.default)
And works great with other types of methods too!
I Know this is a late reply, Surely it will help someone. I have also faced the same issue, and took couple of hours to figure it out.
You need to set encoding in Alamofire request inorder to solve this issue.
encoding: JSONEncoding.default
So the request will be like
Alamofire.request(setUrl(),method:.post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON{
response in

Pass parameter with json field when invoking POST in Alamofire

I have encountered an issue in swift 3:
I have an API which I need to access for data in my app, but the parameter that it demands is in the following format:
"jsonRequest" = {
"header" : "GetLocationListReq",
"accessKey" : "1234567890abcdefghij"
}//this is in json format.
I tried to pass this parameter as dictionary to call the API, but at that point I obtained this message error:
Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed
Any one knows how I can solve the problem?
I think you want to pass these things in header of the request.
for that you need to do like this
let headers = ["header": "GetLocationListReq",
"accessKey": "1234567890abcdefghij"]
Alamofire.request(url, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON{
r in
//do what you want here
}
hope this will work.
try to post this code
let par:[String:Any] = ["jsonRequest":[
"header" : "GetLocationListReq",
"accessKey" : "1234567890abcdefghij"
]]
pass it like that in Alamofire
Alamofire.request(url, method: .post, parameters: par, encoding: JSONEncoding.default, headers: nil).responseJSON{
r in
//do what you want here
}

Alamofire 4.3 can't send JSON request

Iam Trying to send a JSON request using Alamofire but it's not working as a JSON Request here's my JSON :
{"ClientID":"55050","AdminId":"myemail","Password":"123"}
content-type → application/json; charset=utf-8
and here's my code :
import Alamofire
func doLogin(username:String ,password:String) {
let parameters = ["ClientID":"55050" , "AdminId":username,"Password":password]
Alamofire.request("myurl.com", method: .post, parameters: parameters, encoding: JSONEncoding(options: []) ).responseJSON(completionHandler: {
response in
print(response)
})
and here's the response which i am getting
FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}))
By reading the documentation i just need to put header to set the request as application/json
so i added extra parameter header :
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request(ApiKeys().login, method : .post , parameters : parameters, encoding: JSONEncoding.default , headers: headers).responseJSON { response in
}
and now it's working perfectly thanks everyone for trying to help :)
It seems you must have missed header in your request. So, there has been no response.
Your header must be a dictionary [String: String].
let header = ["Content-Type" : "application/json"]
And your sample request should be:
Alamofire.request(getCategoryPath, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: header)
.responseJSON { response in
guard response.result.error == nil else {
print(response.result.error!)
}
print(response.result.value)
}

Alamofire v4 extra argument method in call error

Once I updated to alamofire version 4 I get the error: extra argument method in call
Alamofire.request("www.blabla", method: .put, parameters: parameters, headers: headers, encoding: .JSON)
I already changed it to use "method: .put" like above but I still get the error
I had this issue upgrading to Alamofire 4 and solved it by moving the headers argument and making it the last argument in the call. Also encoding: .JSON should be encoding: JSONEncoding.default.
Call should look like this:
Alamofire.request(url: myUrl, method: .put, parameters: myParams,
encoding: JSONEncoding.default, headers: myHeaders)
What type is parameters? It has to be at least [:] - like:
Alamofire.request(url: myUrl, method: .put, parameters: [:], encoding: JSONEnconding.default, headers: myHeaders)
I broke mind into URLRequest and then just the Alamofire call. Nothing I found worked except breaking it up. I'm using Swift 3 and XCode 8.2.1 and I believe this is swift's sourceKit getting an object wrong.
this
Alamofire.request(url:treeURL!, method: .get, parameters: [:], encoding: JSONEncoding.default, headers: ["Authorization" : app.getToken()])
became this:
var request = URLRequest(url: treeURL!)
request.httpMethod = "GET"
request.allHTTPHeaderFields = ["Authorization" : app.getToken()]
Alamofire.request(request as URLRequestConvertible)
Alamofire.request( "http://....", method: .put , parameters: parameters, encoding: JSONEncoding.default).responseJSON{
response in
if response.result.isSuccess {
//some code
}
}

Resources