I have the Alamofire POST request in the following and the value of my parameter is optional. I would like to allow users to call this API to set the required parameter, even though it is NULL (it's kind of reset to empty default value).
Here's my request and the parameter status is an optional variable that it's expected to be accepting null value:
let URL_UPDATE_STATUS = URL_HOME + "/v1/updateStatus/" + dataId
let parameters: [String : Any] = ["status": status as Any]
Alamofire.request(URL_UPDATE_STATUS, method: .post, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers: self.headers).responseString { response in
switch response.result {
case .success:
print("[Log] Update Status Success")
case .failure(let error):
print("[ERROR] UpdateStatus - \(error)")
APIErrorHandler(response: response, error: error)
}
}
However, I tried several times and it always returns some errors. I tried to be optional and I found that it isn't interpolated (i.e. it becomes "Optional(\"SOME_STATUS\")"). When I tried to force unwrap the string, those null values will cause fatal error. And also, I tried the methods of passing null as the value of the request parameter but it doesn't work anyway.
I don't understand how I should fix it, and could anyone help? Thanks a lot!
You can create the parameters dictionary then assign values to it.
In this case they key would either have a value of not exist.
var parameters: [String : Any] = [:]
parameters["status"] = status
Don't pass null parameter you can check it has value the pass it
check this code
let URL_UPDATE_STATUS = URL_HOME + "/v1/updateStatus/" + dataId
var parameters: [String : Any]? = nil
if let status = status {
parameters = ["status": status]
}
Alamofire.request(URL_UPDATE_STATUS, method: .post, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers: self.headers).responseString { response in
switch response.result {
case .success:
print("[Log] Update Status Success")
case .failure(let error):
print("[ERROR] UpdateStatus - \(error)")
APIErrorHandler(response: response, error: error)
}
}
https://github.com/Alamofire/Alamofire/issues/2407
You just pass nil as the value and Alamofire does all the magic. The problem is most likely somewhere else.
Related
I'm using Alamofire class for api calling. Api is working properly in Postman
please check below two screenshots for reference,
in first image data is passing inside raw body
in second image data is passing inside Headers field
now i'm using this code to call API
//for params i'm sending below parameters
//["phoneNumber":"911234567890", "countryCode" : "91"]
let headers: HTTPHeaders = [
"deviceId" : deviceId,
"osVersion": osVersion,
"deviceType": deviceType,
"resolution":resolution,
"buildNumber":buildNumber]
AF.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers:headers).responseData { (response) in
switch response.result {
case .success(let data):
do {
//let asJSON = try JSONSerialization.jsonObject(with: data)
let asJSON = try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])
// success
print(asJSON)
let res : NSDictionary = (asJSON as AnyObject) as! NSDictionary
successBlock(res)
} catch { // error
print("decoding error:\n\(error)")
}
case .failure(let error):
print(error)
failure(error)
}
}
in all other project above code is working fine for api calling, but here i'm getting below error
{ code = 500; data = ""; message = "Failed to convert value of type 'java.lang.String' to required type 'java.util.Locale'; nested exception is java.lang.IllegalArgumentException: Locale part "en;q=1.0" contains invalid characters"; …………………… NamedValueMethodArgumentResolver.java:125)\n\t... 97 more\n"; status = "INTERNAL_SERVER_ERROR"; timestamp = "01-03-2022 07:55:20"; }
i've try several methods like URLEncoding.default, passing custom header, create custom raw request & passed header inside but nothing works,
AnyOne have solution for this issue?
Thanks in Advance.
As it is throwing error related to Local, I think some language is defined and it doesn't accept * for Accept-Language header, try sending "en" in the header Accept-Language.
Check subtags for language:
http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry :
Test Code:
func callAPI() {
let params: Parameters = ["phoneNumber":"911234567890", "countryCode" : "91"]
let headers = [
"deviceId" : "jdhcbkerfjkr",
"osVersion": "3.2.3",
"deviceType": "ANDROID",
"resolution": "122x122",
"buildNumber": "3.2.1",
"Accept-Language": "en"]
AF.request("[Test-URL]",
method: .post,
parameters: params,
encoding: JSONEncoding.default,
headers: HTTPHeaders.init(headers)).response { response in
print(String(data: response.data!, encoding: .utf8)!)
}
}
I am using the following code:
func readInfo()
{
let customHeader : HTTPHeaders = [
"X-AUTH-TOKEN" : accessToken
]
let body : Parameters = [
:
]
Alamofire.SessionManager.default.session.configuration.timeoutIntervalForRequest = 1000
Alamofire.request(requestAddress, method: .get, parameters: body , encoding: JSONEncoding.default, headers: customHeader).responseJSON {
response in
//utility code
}
}
It works perfect when this runs for the first time but when this is run more than once (in say less than 30 seconds), my server gives the error: o.s.web.servlet.PageNotFound : Request method 'T' not supported
Also I get status code 405 in Alamofire response. This is unexpected since I was sending .get request. Why is this happening and how should I avoid it? I am unable to understand.
Also, note that this is not a server error because the requests work as expected when run on Postman.
Try for Alamofire
var parameters = Parameters()
parameters = [
//Your Params
]
Alamofire.SessionManager.default.session.configuration.timeoutIntervalForRequest = 1000
Alamofire.request("\(url)", method: .get, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON {
response in switch (response.result)
{
case .success(let data):
// your code for success
break
case .failure(let error):
print("Server_Error",error.localizedDescription)
break
}
There were no errors with the cache or timeout. The error was with encoding. I had to save it to URLEncoding.httpBody to make the request work as expected. I still don't understand why it worked once and not for the second time for a certain seconds. Strange case but yes this was the solution. Please leave a comment to help me and others understand why this may have happened.
I really need help with this one. I'm trying to do POST request using Alamofire, but for some reason I'm always getting an error from the title. When I test in POSTMAN, I'm getting okay response. Here is screenshot from POSTMAN, just to get things clearer:
And this is how I'm calling this API in code:
let parameters: Parameters = [
"data": [
"action":"homeimages"
]
]
print("Params: \(parameters)")
Alamofire.request(Constants.API_URL_2, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON {
response in
print("Response: \(response)")
switch response.result {
case .success(let value):
print("Response: \(value)")
break
case .failure(let error):
print(error)
}
}
As far as I know responseserializationfailed error, mostly error with API itself however as you stated, you are getting response in POSTMAN please check below things :
URL(check small/caps well), parameters are correct(check caps and dictionary format as well)
Sometimes we don't need below (optional) parameter , delete this parameter and check
encoding: JSONEncoding.default
I am working on swift project and calling webservice with Alamofire.
But, while calling post method, I am getting following error.
Header file :
let accessTokenHeaderFile = [
"Accept": "application/json",
"Content-Type" :"application/json",
"X-TOKEN" : UtilityClass.sharedInstance.accessTokenString
]
Alamofire.request(urlString, method: .post, parameters: params as? [String:Any], encoding: JSONEncoding.default, headers: accessTokenHeaderFile).responseJSON { response in
requestVC.removeLoader()
switch (response.result) {
case .success:
if response.result.value != nil{
completionHandler (response.result.value)
}
break
case .failure(let error):
failureHandler (error as NSError?)
break
}
}
And the error is
FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
Can anyone suggest me, how to fix this, I tried googling, but whatever I found the answers not helped me.
Error of 3840 saying that the response from server is not a valid JSON string. So you can check you parameters key value may be it’s wrong assign because similar of responseString instead of responseJSON.
Your response is not a valid json hence you're getting this error. Please check the response.response?.statusCode to see what is server returning. And if you want to see the actual response try using responseString or responseData methods instead of responseJSON
e.g.
Alamofire.request(urlString, method: .post, parameters: params as? [String:Any], encoding: JSONEncoding.default, headers: accessTokenHeaderFile). responseData {
You can find out more response methods here
I'm trying to re-create this Postman settings for posting in Alamofire. This is my first time to see an API that requires both Parameters and a body with Raw Json.
I'm done with gathering and formatting my data (either in Json using SwiftyJSON or Dictionary [String : Any] / Parameters) for the said requirement.
While I did see a similar question to this: Postman request to Alamofire request but it doesn't have a valid answer. Assume that I'm quite experienced with posting/getting/etc data from various API but I just don't know how to pass raw data just like in the photo above. Please check out my comments too in the code.
Here's what I'm doing with my function for this request:
/** Apply to job with Shift.
* This service function creates a json data for applying.
*/
func someFuncService(_ job: Job, daySchedules: [(Int, String, Schedule)], withBlock completion: #escaping JobServiceCommonCallBack) {
AuthService.someFunc { (currentCustomer, accessToken) in
guard let lalala = currentCustomer?.id,
let accessT = accessToken else {
completion(LalaErrors.currentCustomerError)
return
}
guard let jobId = job.id else {
completion(LalaErrors.modelError)
return
}
let coreService = LalaCoreService()
let applicantEndpoint = LalaCoreService.Endpoint.Applicant
let parameters = [
"param1" : customerId,
"param2" : jobId,
"accessToken" : accessToken,
"shift" : self.generateDataFromDaySchedules(daySchedules) // this returns [String : Any], can be printed into Json using JSON(x)
] as Parameters
GPLog(classSender: self, log: "FINAL PARAMETER: \(parameters)")
coreService.request = Alamofire.request(
applicantEndpoint,
method: .post,
parameters: parameters,
encoding: URLEncoding.default, // I already have tried .httpbody too.
headers: nil
)
coreService.request {
(response, result) in
if let error = result?.error {
if response!.statusCode == 500 {
completion(GPKitError.newError(description: "Failed to apply. Please contact the admin."))
return
}
completion(error)
return
}
// Success
completion(nil)
return
}
}
}
EDIT: So the question is, what I'm doing wrong here? API returns me status code 500 internal server error.
coreService.request = Alamofire.request(
applicantEndpoint,
method: .post,
parameters: parameters,
encoding: URLEncoding.default, // I already have tried .httpbody too.
headers: nil
)
should be
coreService.request = Alamofire.request(
applicantEndpoint + accessToken,
method: .post,
parameters: parameters,
encoding: JSONEncoding.default,
headers: nil
)