I am trying to save some text data and an image to server using Alamofire but I am getting following error:
FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
My Code:
internal func postContent(forApi Name:String, image:UIImage?, withData payload:[String: String], success: ((_ response:[String: AnyObject])->Void)?, failure: ((Error)->Void)?) {
//create Alamofire request
//if everything was fine call success block with people array passed into it
//if failure occurred, call failure block with error.
if(isConnectedToNetwork()){
let url = SharedConstants.baseURL+Name
print("url "+SharedConstants.baseURL+Name)
Alamofire.upload(multipartFormData: { (multipartFormData) in
if let img = image {
multipartFormData.append(UIImageJPEGRepresentation(img, 0.5)!, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
}
for (key, value) in payload {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
}, to: url, method: .post , headers:nil, encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON(completionHandler: { (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
if let JSON = response.result.value {
print(JSON)
success!(JSON as! [String: AnyObject])
}
else{
failure!(ErrorType.noRecordFound)
}
})
case .failure(let error):
print(error)
}
})
}
else{
failure!(ErrorType.internetNotWorking)
}
}
Thanks in advance
FrontEnd send parameters:
When I parse JSON like this
JSON.parse(params[:delivery_method])
throw error. So we can create a parameter to json.The iOS code is correct, there was problem in backend code. The json was not being properly formed. I corrected the json formation in backend and it started working fine.
URLEncoding(destination: .queryString), headers: headers).responseJSON
Refer:
https://stackoverflow.com/a/43041931/5215474
Check the path in the url may be you are missing some folder.