Read Response From Json Post Call Swift - ios

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

Related

How do I print the body of a http request in swift 3 using Alamofire

I'm trying to make a patch request with Alamofire, in swift 3, with a x-www-form-urlencoded body but it doesn't work. I want to print the body of the request so I can compare with the result when I make the request by postman.
Here is my code
let parameters: [String:AnyObject] = ["conversation[emails_attributes][0][content]":text as AnyObject]
alamofireManager.request(URL, method: .patch, parameters: parameters, encoding: URLEncoding(destination: .httpBody), headers: headers)
.response { httpResponse in
if let error = httpResponse.error {
print(error)
completionHandler(.defaultFailResponse(NSLocalizedString("An errror has occurred",comment:"General Error Title")))
} else {
print("HTTP: \(httpResponse.response?.statusCode)")
if let response = httpResponse.response{
switch response.statusCode {
case 200:
let jsonData = JSON(data: httpResponse.data!)
if (jsonData == nil) {
completionHandler(.defaultFailResponse(NSLocalizedString("Error on Data",comment:"Message error when data is null")))
return
}
print("Message Created")
completionHandler(.defaultSuccessResponse)
default:
completionHandler(.defaultFailResponse(NSLocalizedString("Connection Error",comment:"Connection failed")))
}
print("Failed")
}
}
}
I tried doing print("request body: \(request.HTTPBody)") but it doesn't work, the error message was
error: ambiguous reference to member 'request(_:method:parameters:encoding:headers:)'

How to send request in Alamofire with parameters and headers using POST method in swift

I have a problem with sending a request using Alamofire.
I want to send a POST request with parameters, but I don't know where to put custom header like token.
Here is my code:
let parameters = [
"id": ID,
"recipient_id" : recipientID,
"is_match" : "1"
]
Alamofire.request(.POST, Constants.baseURL + Constants.apiURL + Constants.accept, parameters: parameters, encoding: .JSON)
.validate()
.response { request, response, data, error in
print(request)
print(response)
print(data)
print(error)
}
.responseJSON { response in
switch response.result {
case .Success:
print("Approve Successful")
print("approve \(response)")
case .Failure(let error):
print(error)
}
}
Btw I am using Alamofire 3.4
Alamofire 4.0
let headers = ["Content-Type":"Application/json"]
Alamofire.request(requestString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
print("Request \(response.request)")
print("RESPONSE \(response.result.value)")
print("RESPONSE \(response.result)")
print("RESPONSE \(response)")
switch response.result {
case .success:
case .failure(let error):
}
}
in 3.0 u can also add headers like this . In parameters to func

Getting Invalid response Alamofire

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

Swift 2.0 Alamofire Completion Handler Return Json

My goal is to create a simple function where I pass in a url and it returns me JSON. I have looked around and found little examples of where a completion handler is implemented with Alamofire.
I am also using Swifty Json to help parse it out.
How do I turn what I have here to a function where it returns my Json.
func request() {
Alamofire.request(.GET, API_END_POINT)
.responseJSON {
response in
// swiftyJsonVar is what I would like this function to return.
let swiftyJsonVar = JSON(response.result.value!)
}
}
Swift 3+ and Alamofire 4+
// Call function
myFunction("bodrum") { response in
print(response["yourParameter"].stringValue)
}
// POST
func myFunction(_ cityName:String, completion: #escaping (JSON) -> ()) {
let token = "token"
let parameters = ["city" : cityName]
let headers = ["Authorization": "token"]
let url = URL(string: "url")!
let reqUrl = URLRequest(url: url)
Alamofire.request(reqUrl, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.validate()
.responseJSON { response in
switch response.result {
case .Success:
let jsonData = JSON(data: response.data!)
completion(jsonData)
case .Failure(let error):
MExceptionManager.handleNetworkErrors(error)
completion(JSON(data: NSData()))
}
}
}
Swift 2 and Alamofire 3+
// POST
func myFunction(cityName:String, completion : (JSON) -> ()) {
Alamofire.request(.POST, "url", parameters: ["city" : cityName], encoding: ParameterEncoding.JSON, headers: ["Authorization": "token"])
.validate()
.responseJSON { response in
switch response.result {
case .Success:
let jsonData = JSON(data: response.data!)
completion(jsonData)
case .Failure(let error):
MExceptionManager.handleNetworkErrors(error)
completion(JSON(data: NSData()))
}
}
}
// GET
func myFunction(cityName:String, completion : (JSON) -> ()) {
Alamofire.request(.GET, "url", parameters: ["param1" : cityName], headers: ["Authorization": "token"])
.validate()
.responseJSON { response in
switch response.result {
case .Success:
let jsonData = JSON(data: response.data!)
completion(jsonData)
case .Failure(let error):
MExceptionManager.handleNetworkErrors(error)
completion(JSON(data: NSData()))
}
}
}
// Call function
myFunction("bodrum") { response in
print(response["yourParameter"].stringValue)
}

Alamofire returns .Success on error HTTP status codes

I have a pretty simple scenario that I'm struggling with. I'm using Alamofire to register a user on a rest API. The first call to register is successful and the user can log in. The second call, when trying to register with the same email address should result in a HTTP status code 409 from the server. Alamofire, however, returns a .Success with an empty request and response. I have tested this this API with postman and it correctly returns a 409.
Why is Alamofire not returning .Failure(error), where the error has status code info etc?
Here is the call I run with the same input each time.
Alamofire.request(.POST, "http://localhost:8883/api/0.1/parent", parameters: registrationModel.getParentCandidateDictionary(), encoding: .JSON).response(completionHandler: { (req, res, d, e) -> Void in
print(req, res, d, e)
})
From the Alamofire manual:
Validation
By default, Alamofire treats any completed request to be successful,
regardless of the content of the response. Calling validate before a
response handler causes an error to be generated if the response had
an unacceptable status code or MIME type.
You can manually validate the status code using the validate method, again, from the manual:
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { response in
print(response)
}
Or you can semi-automatically validate the status code and content-type using the validate with no arguments:
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.responseJSON { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}
If using response, you can check the NSHTTPURLResponse parameter:
Alamofire.request(urlString, method: .post, parameters: registrationModel.getParentCandidateDictionary(), encoding: JSONEncoding.default)
.response { response in
if response.response?.statusCode == 409 {
// handle as appropriate
}
}
By default, 4xx status codes aren't treated as errors, but you can use validate to treat it as an such and then fold it into your broader error handling:
Alamofire.request(urlString, method: .post, parameters: registrationModel.getParentCandidateDictionary(), encoding: JSONEncoding.default)
.validate()
.response() { response in
guard response.error == nil else {
// handle error (including validate error) here, e.g.
if response.response?.statusCode == 409 {
// handle 409 here
}
return
}
// handle success here
}
Or, if using responseJSON:
Alamofire.request(urlString, method: .post, parameters: registrationModel.getParentCandidateDictionary(), encoding: JSONEncoding.default)
.validate()
.responseJSON() { response in
switch response.result {
case .failure:
// handle errors (including `validate` errors) here
if let statusCode = response.response?.statusCode {
if statusCode == 409 {
// handle 409 specific error here, if you want
}
}
case .success(let value):
// handle success here
print(value)
}
}
The above is Alamofire 4.x. See previous rendition of this answer for earlier versions of Alamofire.
if you use validate() you'll loose the error message from server, if you want to keep it, see this answer https://stackoverflow.com/a/36333378/1261547
Here is my code for AlamoFire error catching:
switch response.result {
case .success(let value):
completion(.success(value))
case .failure(var error):
var errorString: String?
if let data = response.data {
if let json = try? (JSONSerialization.jsonObject(with: data, options: []) as! [String: String]) {
errorString = json["error"]
}
}
let error = MyError(str: errorString!)
let x = error as Error
print(x.localizedDescription)
completion(.failure(x))
}
and the MyError class difinition:
class MyError: NSObject, LocalizedError {
var desc = ""
init(str: String) {
desc = str
}
override var description: String {
get {
return "MyError: \(desc)"
}
}
//You need to implement `errorDescription`, not `localizedDescription`.
var errorDescription: String? {
get {
return self.description
}
}
}

Resources