Post multiple object data in alamofire - ios

The number of posts is available in StackOverflow but i can't get the solution, I am using Alamofire Library and post my result to hit API but I'm not able to get the result please help me to fix it.
{
"People":{ "Prefix": "Mr.",
"FirstName": "Eric",
"MiddleName": null,
"LastName": "John",
"FullName": "Smith GOldi6",
"Email1": "abc123#example.com",
"Email2": null,
"PhoneNumber1": "0000",
"PhoneNumber2": null,
"DateOfBirth": "1975-01-01T00:00:00",
"Status": 3,
"DeleteFlag": true,
"Comments": null,
"Description": null,
"UserName": "abc123"
},
"Password": "password1"
}
this is the result which I create in parameters to post.
Alamofire.request(signup_api, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseJSON { (response) in
switch response.result {
case .success(let data) :
let json = JSON(data)
print("response.result = \(response.result)")
print("response = \(response)")
let resJson = JSON(response.result.value!)
print("success = \(resJson)")
if (resJson.count == 0) {
if (resJson.null == nil) {
// self.DimBackground.isHidden = true
// self.activator.stopAnimating()
}
return
}
if let err = response.error{
print("err === \(err)")
return
}
return
case .failure(let _error):
print("_error = \(_error)")
print("false")
print("response.result = \(response.result)")
print("response = \(response)")
print("Network Problem: There might be an issue with your internet connection, or server not responding. Please try again.")
return
}
}
This shows this error:
_error = responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error:
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around
character 0." UserInfo={NSDebugDescription=Invalid value around
character 0.})) false response.result = FAILURE response = 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.}))

if you are getting proper JSON response than there should be issue in your condition
if (resJson.count == 0)
Actually there should be status (true/false) in your response so you get idea which action you need to take if status is true than you have to get proper data from response and processed for further. else you have to show error message and stop for processed further.

Related

Getting Code=3840 "Invalid value around character 0."

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! :(

POST Request Swift 3.0 Alamofire

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.

Login with Alamofire post method

I am trying to login like that code:
let loginRequest = [
"UserName" : self.txtUserName.text! as String,
"Password" : self.txtPassword.text! as String
]
let serverUrl = ServerPath.Path + "/Test/login"
Alamofire.request(.POST, serverUrl, parameters: loginRequest,encoding: .JSON).responseJSON
{
response in switch response.result {
case .Success(let data):
...
...
case .Failure(let error):
print("Request failed with error: \(error)")
}
always getting error
Request failed with error: Error Domain=NSCocoaErrorDomain Code=3840
"Invalid value around character 0."
UserInfo={NSDebugDescription=Invalid value around character 0.}
but I'm trying to static like that operation completed as success
let loginRequest = [
"UserName" : "Test",
"Password" : "123"
]
Just change responseJson with resonseString or responseData
your error will gone.
Running the code actually works fine. The error comes from responseJSON which means the content being sent back from the server is not proper JSON.

getting nil value while calling api (alamofire)

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

Alamofire invalid value around character 0

Alamofire.request(.GET, "url").authenticate(user: "", password: "").responseJSON() {
(request, response, json, error) in
println(error)
println(json)
}
This is my request with Alamofire, for a certain request it sometime works, but sometimes i get:
Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x78e74b80 {NSDebugDescription=Invalid value around character 0.})
I've read that this can be due to invalid JSON, but the response is a static json string that i have validated in JSON validator as valid. It does contain å ä ö characters and some HTML.
Why am i getting this error sometimes?
I also faced same issue. I tried responseString instead of responseJSON and it worked. I guess this is a bug in Alamofire with using it with django.
In my case , my server URL was incorrect. Check your server URL !!
I got same error while uploading image in multipart form in Alamofire as i was using
multipartFormData.appendBodyPart(data: image1Data, name: "file")
i fixed by replacing by
multipartFormData.appendBodyPart(data: image1Data, name: "file", fileName: "myImage.png", mimeType: "image/png")
Hope this help someone.
May this Help YOu
Alamofire.request(.GET, "YOUR_URL")
.validate()
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
}
The same issue happened to me and it actually ended up being a server issue since the content type wasn't set.
Adding
.validate(contentType: ["application/json"])
To the request chain solved it for me
Alamofire.request(.GET, "url")
.validate(contentType: ["application/json"])
.authenticate(user: "", password: "")
.responseJSON() { response in
switch response.result {
case .Success:
print("It worked!")
print(response.result.value)
case .Failure(let error):
print(error)
}
}
I got the same error. But i found the solution for it.
NOTE 1: "It is not Alarmofire error", it's bcouse of server error.
NOTE 2: You don't need to change "responseJSON" to "responseString".
public func fetchDataFromServerUsingXWWWFormUrlencoded(parameter:NSDictionary, completionHandler: #escaping (_ result:NSDictionary) -> Void) -> Void {
let headers = ["Content-Type": "application/x-www-form-urlencoded"]
let completeURL = "http://the_complete_url_here"
Alamofire.request(completeURL, method: .post, parameters: (parameter as! Parameters), encoding: URLEncoding.default, headers: headers).responseJSON { response in
if let JSON = response.result.value {
print("JSON: \(JSON)") // your JSONResponse result
completionHandler(JSON as! NSDictionary)
}
else {
print(response.result.error!)
}
}
}
This is how I managed to resolve the Invalid 3840 Err.
The error log
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
It was with Encoding Type used in the Request, The Encoding Type used should be acceptedin your Server-Side.
In-order to know the Encoding I had to run through all the Encoding Types:
default/
methodDependent/
queryString/
httpBody
let headers: HTTPHeaders = [
"Authorization": "Info XXX",
"Accept": "application/json",
"Content-Type" :"application/json"
]
let parameters:Parameters = [
"items": [
"item1" : value,
"item2": value,
"item3" : value
]
]
Alamofire.request("URL",method: .post, parameters: parameters,encoding:URLEncoding.queryString, headers: headers).responseJSON { response in
debugPrint(response)
}
It also depends upon the response we are recieving use the appropriate
responseString
responseJSON
responseData
If the response is not a JSON & just string in response use responseString
Example: in-case of login/ create token API :
"20dsoqs0287349y4ka85u6f24gmr6pah"
responseString
I solved using this as header:
let header = ["Content-Type": "application/json",
"accept": "application/json"]
In my case, there was an extra / in the URL .
Maybe it is too late but I solved this problem in another way not mentioned here:
When you use .responseJSON(), you must set the response header with content-type = application/json, if not, it'll crash even if your body is a valid JSON. So, maybe your response header are empty or using another content-type.
Make sure your response header is set with content-type = application/json to .responseJSON() in Alamofire work properly.
Hey guys this is what I found to be my issue: I was calling Alamofire via a function to Authenticate Users: I used the function "Login User" With the parameters that would be called from the "body"(email: String, password: String) That would be passed
my errr was exactly:
optional(alamofire.aferror.responseserializationfailed(alamofire.aferror.responseserializationfailurereason.jsonserializationfailed(error domain=nscocoaerrordomain code=3840 "invalid value around character 0." userinfo={nsdebugdescription=invalid value around character 0
character 0 is the key here: meaning the the call for the "email" was not matching the parameters: See the code below
func loginUser(email: String, password: String, completed: #escaping downloadComplete) {
let lowerCasedEmail = email.lowercased()
let header = [
"Content-Type" : "application/json; charset=utf-8"
]
let body: [String: Any] = [
"email": lowerCasedEmail,
"password": password
]
Alamofire.request(LOGIN_USER, method: .post, parameters: body, encoding: JSONEncoding.default, headers: header).responseJSON { (response) in
if response.result.error == nil {
if let data = response.result.value as? Dictionary<String, AnyObject> {
if let email = data["user"] as? String {
self.userEmail = email
print(self.userEmail)
}
if let token = data["token"] as? String {
self.token_Key = token
print(self.token_Key)
}
"email" in function parameters must match the let "email" when parsing then it will work..I no longer got the error...And character 0 was the "email" in the "body" parameter for the Alamofire request:
Hope this helps
I was sending the improper type (String) to the server in my parameters (needed to be an Int).
Error was resolved after adding encoding: JSONEncoding.default with Alamofire.
Alamofire.request(urlString, 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)
}
}
The application I was working on this morning had the same error. I believed it to be a server side error since I was unable to upload a user image.
However, upon checking my custom API, I realized that after adding an SSL certificate to my website that I had not updated the api.swift URLs, the data was unable to post:
let HOME_URL = "http://sitename.io"
let BASE_URL = "http://sitename.io/api"
let UPLOAD_URL = "http://sitename.io/api/user/upload"
I changed the URL's to https://. Problem solved.
In my case I have to add this Key: "Accept":"application/json" to my header request.
Something like this:
let Auth_header: [String:String] = ["Accept":"application/json", "Content-Type" : "application/json", "Authorization":"Bearer MyToken"]
I hope that this can help someone.
I face same issue and problem is in params.
let params = [kService: service,
kUserPath: companyModal.directory_path,
kCompanyDomain: UserDefaults.companyDomain,
kImageObject: imageString,
kEntryArray: jsonString,
kUserToken: UserDefaults.authToken] as [String : Any]
companyModal.directory_path is url. it coerced from string to any which create issues at server side. To resolve this issue I have to give default value which make it string value.
let params = [kService: kGetSingleEntry,
kUserPath: companyModal.directory_path ?? "",
kCompanyDomain: UserDefaults.companyDomain,
kUserToken: UserDefaults.authToken,
kEntryId: id,
] as [String: Any]
Probably you have "/" at the end of your path. If it is not GET request, you shouldn't put "/" at the end, otherwise you'll get the error
I Changed mimeType from "mov" to "multipart/form-data".
Alamofire.upload(multipartFormData: { (multipartFormData) in
do {
let data = try Data(contentsOf: videoUrl, options: .mappedIfSafe)
let fileName = String(format: "ios-video_%#.mov ", profileID)
multipartFormData.append(data, withName: "video", fileName: fileName, mimeType: "multipart/form-data")
} catch {
completion("Error")
}
}, usingThreshold: .init(), to: url,
method: .put,
headers: header)
Worked for me.. :)
For my case:
let header = ["Authorization": "Bearer \(Authserices.instance.tokenid)"]
I forgot the space before \ (after Bearer)
In my case error was due to duplicate email. You can recheck your API on postman to see if response there is OK or not.
In my case, I tried using Postman to get API and this error come from backend.

Resources