Getting Invalid response Alamofire - ios

Hello i am using Alamofire but i am getting "Invalid JSON." in the response and i have used following code-
parametersV = ["username":amrit21#yopmail.com, "password":123456]
let headers = ["Content-Type": "application/json", "x-csrf-token":""]
Alamofire.request(.POST, "https://dev.staffingevolution.com/api/user/login", parameters: parametersV, headers: headers).responseJSON { 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: \(JSON)")
}
}

I Solved it
let parametersV = ["username":"amrit21#yopmail.com", "password":"123456"]
Alamofire.request(.POST, "https://dev.staffingevolution.com/api/user/login", parameters: parametersV, encoding: .JSON)
.responseJSON { response in
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
It was a problem was encoding you were not encoding your JSON request. use encoding: .JSON

Some times when in response there is not proper JSON then piece of code .responseJSON { response in throws exception and we can't see what type of response has been received. in such case we can print it to console before converting to .responseJSON { response in
Below is full example
public func deleteImage(_ photoId: Int) {
let requestURL = URL(string: APPURL.BASE_API_URL + "postApi/deletePostPhoto")!
let paramDict: [String: String] = ["photoId": String(photoId), "accessKey": APP_DELEGATE.loggedInUser.accessKey, "language":APP_DELEGATE.language.lowercased()]
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in paramDict {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
},
usingThreshold:UInt64.init(),
to: requestURL ,
method:.post,
headers:nil,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
// this is point where we can get actual response recieved from server, it may have some html , xml or anything
upload.responseData(completionHandler: { response in
print(response)
let responseData = String(data: response.data!, encoding: String.Encoding.utf8)
print("responseData=",responseData ?? "none")
})
// if there is proper JSON recieved it will be executed otherwise it will fall in failure
upload.responseJSON { response in
if((response.result.value) != nil) {
let swiftyJsonVar = JSON(response.result.value!)
print("response JSON: ",swiftyJsonVar)
}
else {
let error = response.error
print(error?.localizedDescription ?? "")
}
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
}
})
}

Related

How to send request in Alamofire 4.0 only with parameters and Body using POST method in swift?

I am using like this, but in this case, I need to call API with parameters and Body. Please help me. Thanks in advance.
Alamofire.request(postUrl, method: .post, parameters: params, encoding: CustomPostEncoding(), headers: nil).validate().responseJSON{ response in
switch response.result
{
case .success:
MBProgressHUD.hide(for: self.view, animated: true)
if let val = response.result.value
{
let json = JSON(val)
print(json)
}
case .failure(let error):
print(error)
}
}
var url = "http://..."
let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]
let url = NSURL(string:"url" as String)
request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody , headers: _headers).responseJSON(completionHandler: {
response in response
let jsonResponse = response.result.value as! NSDictionary
if jsonResponse["access_token"] != nil
{
access_token = String(describing: jsonResponse["accesstoken"]!)
}
})
Refrence :- POST request with a simple string in body with Alamofire
use your parameters instead of class_id ,and time.
func listOfClassesData(url: String,class_id: String,time: String,redClassesData : [String: Any] ,completionHandler:#escaping (Bool) -> ()){
let Auth_header = ["Authorization" : "Bearer "+getBearerToken()]
let paameters:Parameters = [
"class_id" : class_id,
"time" :time,
]
print(url,Auth_header)
Alamofire.request(url, method: .post, parameters: paameters, encoding: JSONEncoding.default, headers: Auth_header)
.responseJSON { response in
print(response)
switch response.result{
case .success:
let statusCode: Int = (response.response?.statusCode)!
switch statusCode{
case 200:
if let json = response.result.value{
completionHandler(true)
}
break
default:
completionHandler(false)
break
}
break
case .failure:
completionHandler(false)
break
}
}
}
let url = "your api url"
let param = ["user":"user#test.com","pass":"12345"]
Alamofire.request(url, method: .post , parameters: param)
.validate()
.responseJSON {
response in
switch response.result{
case .success:
var jsonResult = [String:AnyObject]()
do
{
//Get response successfully of api
jsonResult = try JSONSerialization.jsonObject(with: response.data!, options: []) as! [String:AnyObject]
print(jsonResult)
}
catch let error as NSError {
//get error if there is any problem in response of api.
print("--->",error)
}
case .failure(let error):
//get error if there is any problem while calling api.
print("---->",error)
}
}

Access JSON value from Alamofire response

I am making a request to a local server that returns the following JSON:
{"session_key":"somecodexyz1234"}
The following code is is used to attempt to print the session_key value. But this is always evaluated tonil`.
Alamofire.request(url, method: .post, parameters: parameters).responseJSON(completionHandler: {
response in
print("Request: \(String(describing: response.request))")
print("Response: \(String(describing: response.response))")
print("Response code: \(String(describing: response.response?.statusCode))")
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}}
if response.data != nil {
let json = JSON(data: response.data!)
// changes
if let arr : NSArray = json as? NSArray
{
let sk = arr.value(forKey: "session_key") as? String
if sk != nil {print(sk)}
}
}
The following is output (the print(sk) is not executed as it is nil):
Request: Optional(http://127.0.0.1:5000/code)
Response: Optional(<NSHTTPURLResponse: 0x60800023f260> { URL: http://127.0.0.1:5000/code } { status code: 200, headers {
"Content-Length" = 40;
"Content-Type" = "application/json";
Date = "Sat, 23 Sep 2017 06:02:25 GMT";
Server = "Werkzeug/0.12.2 Python/3.4.3";
} })
Response code: Optional(200)
Data: "{\"session_key\":\"somecodexyz1234\"}"
Use below code to get response from almofire in json. In Your code, your are directly checking response.data instead of first check response.result as below.
Alamofire.request(requestURL, method:.post, parameters: param as? Parameters, encoding: URLEncoding(destination: .httpBody), headers: headers).responseJSON(completionHandler: { (response) in
switch response.result
{
case .success(let responseJSON):
// If request success then you will get response in json here
if responseJSON is String{
print("Reponse is string")
}
else if responseJSON is NSDictionary{
print("Reponse is Dictionary")
}
else if responseJSON is NSArray{
print("Reponse is Array")
}
else{
print("Any object")
return
}
print("Response : \((dicResponse)")
break
case .failure(let error):
// If request is failure then got error here.
break
}
})
You are using SwiftyJSON so why you again convert let arr : NSArray = json as? NSArray like this. You can simply do like this.
Alamofire.request(url, method: .post, parameters: parameters).responseJSON(completionHandler: {
response in
print("Request: \(String(describing: response.request))")
print("Response: \(String(describing: response.response))")
print("Response code: \(String(describing: response.response?.statusCode))")
if response.result.isSuccess, let result = response.result.value {
let json = JSON(result)
// Here is your session key
let sk = json["session_key"].stringValue
} else {
//Failure
}
})

how to post id and password by alamofire

all.
I study iOS and alamofire.
I tried to connect Login API url. It is correctly operating.
this is code.
var rTest = Alamofire.request(self.authLoginUrl, method: .post)
.responseJSON{ 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: \(JSON)")
}
}
}
and i want to post id and password
let params = ["Username": "ryulstory", "Password": "1234!"]
var rTest = Alamofire.request(self.authLoginUrl, method: .post, Parameters: params)
.responseJSON{ 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: \(JSON)")
}
}
}
there are error :Extra argument 'method' in call.
the error doesn't show if i don't put params.
what is problem? could you help me?
best regards.
Assuming your backend receives and returns JSON, this should work
let params: Parameters = [
"Username": "ryulstory",
"Password": "1234!"
]
//if server accepts and returns JSON
Alamofire.request(self.authLoginUrl, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).validate().validate(contentType: ["application/json"])
.responseJSON() { response in
switch response.result {
case .success:
print("Success")
case .failure(let error):
print("Failure")
}
}
.response { response in
log.debug("Request: \(String(describing: response.request))")
log.debug("Response: \(String(describing: response.response))")
log.debug("Error: \(String(describing: response.error))")
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
log.debug("Data: \(utf8Text)")
}
}

Alamofire .responseJSON doesn't work with JSON response

I'm using alamofire to upload an image.
This is sign up API where you can sign up with your profile photo (this is what I have to upload)
So my code is this (I will replace print(JSON) with another code; this is just for testing what's wrong)
func makeUploadRequest(url: String?) {
let imageData = NSData(data: UIImageJPEGRepresentation(self.userImage.image!, 1)!)
Alamofire.upload(.POST, url!, headers: ["Content-Type":"application/json"], multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imageData, name: "image_file_1")
}, encodingCompletion: {
encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { (JSON) in
print(JSON)
}
case .Failure(let encodingError):
//Show Alert in UI
print(encodingError)
}
})
}
but when I run this code, I come across with this message:
FAILURE: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around
character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
I know why I get this message, it's because the response is not in JSON format.
But the response is actually JSON
{
result: "success",
msg: "",
data: {...}
}
When I test the API with URL, it works just fine.
When I used .responseString instead of .responseJSON: it said something about ASP.NET
.response:
(Optional(<NSMutableURLRequest: 0x7f8353217d50> { URL: url }),
Optional(<NSHTTPURLResponse: 0x7f8353099040> { URL: url }
{ status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 5136;
"Content-Type" = "text/html; charset=utf-8";
Date = "Tue, 26 Apr 2016 06:09:03 GMT";
Server = "Microsoft-IIS/7.5";
"X-AspNet-Version" = "2.0.50727";
"X-Powered-By" = "ASP.NET";
} }), Optional(<3c68746d ... 2e2d2d3e>), nil)
Any help? Thanks in advance!
Try to replace Success block :-
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
AppHelper.hideLoadingSpinner()
if response.result.value is NSNull
{
print("Response nil")
}
else
{
if let JSON = response.result.value {
var mydict = NSMutableDictionary()
mydict = JSON as! NSMutableDictionary
if (self.delegate != nil){
print("response:--------------------\n %#",mydict)
}
}
else
{
print("response not converted to JSON")
}
}
upload.response(completionHandler: { (request, response, data, error) -> Void in
NSLog("upload.response : data : %#", String(data: data!, encoding: NSUTF8StringEncoding)!)
NSLog("upload.response : response : %#", response!)
})
}
Check your result if it's a failure or success before getting the value. E.g.:
switch response.result {
case .Success(let value):
print("Value: \(value)")
break
case .Failure(let error):
print("Error: \(error)")
break
}

Read Response From Json Post Call Swift

In the java app we get response from the REST as String by using de below code.
String response = performPostCall(wmeAPI.vote("" + rowItem.getPoll_id()), has);
In swift I am making post call with Alamofire
I made post call
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON).responseString
{ response in switch response.result {
case .Success(let JSON):
print("Success \(JSON)")
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
How can I get the response string from this post call.
You need to use response JSON
So, Change responseString to responseJSON
For Example :
Alamofire.request(.GET, "YOUR_URL").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
print(swiftyJsonVar)
}
}
For POST call :
Alamofire.request(.POST, "YOUR_URL", parameters: nil, encoding: ParameterEncoding.JSON, headers: nil).responseJSON { (responseObject) -> Void in
print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
print(resJson)
}
if responseObject.result.isFailure {
let error : NSError = responseObject.result.error!
print(error)
}
}
if you check Alamofire Doc., there is already define the things that how to get response String and how to get response JSON
Response JSON handler
Alamofire.request(.GET, "https://httpbin.org/get")
.responseJSON { response in
debugPrint(response)
}
Response String handler
Alamofire.request(.GET, "https://httpbin.org/get")
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
}
Chained Response Handlers
Alamofire.request(.GET, "https://httpbin.org/get")
.responseString { response in
print("Response String: \(response.result.value)")
}
.responseJSON { response in
print("Response JSON: \(response.result.value)")
}
Refer Alamofire Usage

Resources