i am using alamofire to call api. but in this particular api i am getting nil value as a response. actually when i hit my api in my browser its working pretty well.
here is my code
func web()
{
request(.GET, "http://www.horecasupply.nl/AJAX?function=appStructure", parameters: nil, encoding: .JSON).responseJSON { (response : Response<AnyObject, NSError>) -> Void in
if response.result.value != nil {
print(response.result.value)
}
}
}
getting nil value and when i print respose its showing me
Printing description of response.result.Failure:
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 1."
UserInfo={NSDebugDescription=Invalid value around character 1.}
EDIT 1:: tried responsestring instead of responsejson.
but getting different kind of response so how can i convert it?
\r\n\r\n\r\n\r\n</script>\r\n DD_belatedPNG.fix(\'img, .png_bg\'); //fix any or .png_bg background-images </script>\r\n\r\n\r\n</script>\r\n</script>-->\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n")
Give this code a shot, this should work:
Alamofire.request(.GET, "http://www.horecasupply.nl/AJAX?function=appStructure").responseJSON { response in
if response.result.value != nil {
print(response.result.value)
}
}
Related
I am facing a very strange issue while calling APIs,
When I call API first time, I am getting below error,
FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
and in failure block, I again call the same API and I got the proper response.
I have used Alamofire for API Calls.
I tried very hard to figure out the solution but no luck yet.
Below is my code,
Alamofire.request(URL(string: baseURL + url.rawValue)!, method: method, parameters: param, encoding: encoding, headers: header).responseJSON { (response) -> Void in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
print(response)
let responseJson = JSON(response.result.value as Any)
if let statusCode = response.response?.statusCode
{
print(statusCode)
let status = accepTableStatusCodes.contains(statusCode)
switch status {
case true:
success(responseJson)
break
default:
if let message = responseJson.dictionaryObject?[ApiKeys.message] as? String{
if message != ApiKeys.Unauthorized {
DELEGATE.window!.rootViewController?.view.showToast(toastMessage: message, duration: 0.3)
}
}
failure(responseJson)
break
}
} else {
print("Something went wrong")
}
}
I have tried by changing responseJSON to responseString. Nothing is working.
In header I am passing below values,
header = [ApiKeys.Authorization : "Bearer \(user.token ?? "")", "Accept" : "application/json","Content-Type": "application/json"]
I don't understand why it is throwing an error on the first call and the same call gives a proper response in the second call. In my project, I have integrated almost 10+ APIs and in each API, this same thing is happening.
Really weird and strange behavior! :(
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 am trying to do a .POST request with Alamofire in Swift 3. I´ve written the following function
func postToken(Token: String) {
let parameters : [String:Any] = ["api_key":"ivaomobileapp", "function":"login", "IVAOTOKEN=":"\(Token)"]
Alamofire.request("URL", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(data)
}
break
case .failure(_):
print(response.result.error as Any)
break
}
}
}
But the code doesn´t work, it gives the following error:
Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
This is the same request in CURL(UNIX)
curl https://whatever -X POST -F 'api_key=ivaomobileapp' -F 'function=Login' -F 'IVAOTOKEN=whatever'
What am I doing wrong?
Thanks
I think you handle the addition of the IVAOTOKEN parameter in the wrong way, causing issues, perhaps creating a malformed dictionary. Perhaps your parameters should look like the following:
let parameters : [String:Any] = [
"api_key": "ivaomobileapp",
"function": "login",
"IVAOTOKEN": Token
]
Alamofire will add the quotes around the Token variable, as it is a String. The result should be that the following is sent to the server:
{
"api_key": "ivaomobileapp",
"function": "login",
"IVAOTOKEN": "TOKENVALUE"
}
Response from a server isn't valid json try using responseString, responseData or response to figure out what the issue is.
I'm using Alamofire to get data from my server. However, it doesn't catch the error, as the error returned is nil. I've tested with AFNetworking, and it works fine. For both operation, the status code returned is 401 Unauthorized . Is there's something with my code?
I'm using GrapeAPI for my backend. All it does is just to return the error on fail request
GrapeAPI
error!('Unauthorized', 401)
AFNetworking
manager.GET("someUrl", parameters: nil, success: { (_, object) in
}, failure: { (operation, error) in
// These are the outputs. I'm not assigning any values
// error.localizedDescription = "Request failed: unauthorized (401)"
// statusCode = 401
})
Alamofire
Alamofire.request(.GET, "url", parameters: nil)
.response { (a,b,data,error) in
// These are the outputs. I'm not assigning any values
// error = nil
// data = {"error":"Unauthorized"}
// statusCode = 401
}
I can check the failure using the statusCode. But I prefer to check the error object instead. However, since the error is nil in Alamofire, it's quite confusing to check whether the request has failed or not.
As Matt has mentioned in the comment, I need to add .validate() before calling .response(). This is by design. Final code as below:
Alamofire.request(.GET, "url", parameters: nil)
.validate()
.response { (a,b,data,error) in
// error won't be nil now
// and statusCode will be 401
}
Read this detailed explanation(thanks!) for more information.
Alamofire does not see 401 Unauthorized as an error as it is an valid return. In your comment code you are assigning a value to error not checking it for error, it should be:
Alamofire.request(.GET, "url", parameters: nil)
.response { (a,b,data,error) in
if error != nil{
println(error.localizedDescription)
} else {
if let data = data{
//You should probably use a switch statement here
if data.statusCode == 401 {
println("Unauthorized")
} else if data.statusCode == 200 {
println("Success")
}
}
}
I am not sure if i understand correctly your problem, but I hope that help!
Throughout my project I can perfectly check Alamofire responses and data for
if fooData != nil {
//do stuff
}
somehow in this instance Swift seems to have problems checking what the actual incoming type is
what I get if I print it is
<null>
what is this supposed to be? An array of null? Casts to NSDictionary or NSArray both fail.
The Rest response is the same as always throughout the project where I will potentially receive a null value and it gets catched everywhere else.
€dit with more code:
my request:
Alamofire.request(.GET, "\(CurrentConfiguration.serverURL)/api/users/\(CurrentConfiguration.currentUser.id)/friends/\(targetUser)",encoding:.JSON)
.validate()
.responseJSON {(request, response, friendData, error) in
if friendData != nil {
println(friendData!)
//this is where the app obviously crashes as there is nothing inside of "friendData"
let resp = friendData as NSDictionary
//load friendData into the UI
}
}
the print statement gives me the above mentioned null representation, but obviously does not recognize as nil
the response from the node backend comes as
index.sendJsonResponse(res, 200, null);
Try this code in Playground:
let fooData:AnyObject = NSNull()
println(fooData)
It prints <null>.
fooData is not nil, but a instance of NSNull