Access JSON value from Alamofire response - ios

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

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

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

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:)'

I have a url which posts some data to the server. How do i convert it to alamofire post request method with all parameters mentioned in URL

let url = "(InsertAsset)?customerID=(vmanagerappDelegate.cust_Id!)&assetTag=(self.txt_AssetTag.text! as String)&modelID=(modelObject)&statusID=(statusObject)&serial=(self.txt_Serial.text! as String)&assetName=(self.txt_AssetName.text! as String)&purchaseDate=(selectedPurchaseDate)&supplierID=(supplierObject)&purchaseCost=(purchaseCostObject)&warranty=(self.txt_Warranty.text! as String)&notes=(notesObject)&locationID=(locationObject)&ownerID=(ownerObject)&addUserID=(vmanagerappDelegate.userId as String)&saleEndDate=(self.txt_Sale_End_Date.text! as String)&softwareMaintainenceEndDate=(self.txt_Software_Maintainence_End_Date.text! as String)&supportEndDate=(self.txt_Support_End_Date.text! as String)&MacAddress=(self.txt_Mac_Address.text! as String)&sitekey=testing"
Hi you can create dictionary like following to send parameter as dictionary in Alamofire :
var dicParam = Dictionary<String,AnyObject>()
dicParam[“customerID”] = vmanagerappDelegate.cust_Id!
dicParam[“assetTag”] = self.txt_AssetTag.text! as String
dicParam["modelID"] = modelObject
In Alamofire pass above dictionary as parameters along with your URL like following :
Alamofire.request("Your URL", method: .post, parameters: dicParam, encoding: URLEncoding(destination: .queryString), headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
try creating a dicitonary
let params:Dictionary<String, AnyObject> = ["customerID":vmanagerappDelegate.cust_Id!,"assetTag":self.txt_AssetTag.text,"modelID":modelObject] //similarly add all params to Dict
if you want to add some headers create dicitonary Header for them too and pass in Alamofire.request(.POST,url,parameters: params,headers:Header,encoding: .JSON)
a example for post request
func remotePOSTServiceWithParameters(urlString : String , params : Dictionary<String, AnyObject> , callback:(data: Dictionary<String, AnyObject>?, error: NSError? ) -> Void) {
print("Request POST URL:\(urlString) PARAMS:\(params)")
Alamofire.request(.POST,urlString,parameters: params,encoding: .JSON)
.validate()
.responseJSON {
response in
guard response.result.error == nil else {
print("Error for POST :\(urlString):\(response.result.error!)")
//
callback(data: nil , error: response.result.error! )
return
}
if let value = response.result.value {
print("JSON: \(value)")
if let result = value as? Dictionary<String, AnyObject> {
print("Response for POST :\(urlString):\(value)")
callback(data:result , error: nil )
}
}
}
}

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

Resources