Alamofire get response from POST - swift

How can I get response from POST method using Alamofire?
I have next POST method:
let parameters = [
"Firstname": "\(first_name)",
"Lastname": "\(last_name)",
];
Alamofire.request(.POST, URLString, parameters: parameters as? [String : AnyObject], encoding: .JSON)
And when this is done, I want to get a response my record with ID and other fields. How can I do it?

You can write a method like this...
func getData(result: (response: NSMutableArray!, error : NSError!) -> Void){
let parameters = [
"Firstname": "\(first_name)",
"Lastname": "\(last_name)", ];
//Request to fetch data from the server
Alamofire.request(.POST,URLString, parameters: parameters,encoding:.JSON).responseJSON
{ response in switch response.result {
case .Success(let jsonData):
result(response: jsonData as! NSMutableArray, error: nil)
case .Failure(let error):
result(response: nil, error: error)
}
}
}//getData
And call above method as...
YOURCLASSOBJECT.getFeedData( { (response, error) -> Void in
//If data is fetched successfully
if(response != nil){
print("Response : \(response)")
}
})

Alamofire.request(.POST, URLString, parameters:parameters,encoding:.JSON).responseJSON { (response) -> Void in
if response.result.value != nil {
print(response.result.value)
}
}

Related

the alamofire isn't doing a proper connection to the api

i am trying to get a response that contain json from openweathermap api,
but from the debugger it seems that when he get to the code block of alamofire its just skips it
here is the block of code that i am using for this task
func printJson(){
Alamofire.request("https://api.openweathermap.org/data/2.5/find?appid=6ad1f143546b8c6d761ecbda6a34a005&q=yavne", method: .get).responseJSON { response in
if response.data != nil {
var json : JSON
do{
json = try JSON(data: response.data!)
print(json)
}catch{}
}
}
}
Use this helper class to make API calls.
class NetworkHandler {
static let shared = NetworkHandler()
func sendRequest(withUrl url:String,andBody body:[String:Any]? = [:],
completionHandler: #escaping ((_ status: Bool,_ response:Any) -> Void)) {
DispatchQueue.global(qos: .userInitiated).async {
Alamofire.request(url, method: .post, parameters: body,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
guard response.response?.statusCode == 200 else{
completionHandler(false,"Service Temporarily Unavailable.\nPlease check your internet connection or contact your Service provider.")
return
}
switch response.result {
case .success:
completionHandler(true,response.value!)
break
case .failure(let error):
completionHandler(false,error.localizedDescription)
}
}
}
}
}

Swift 4 error when POST data via HTTP

I have problem when send complain data to server with API.
My send func. As result i got 404 error (screenshot below)
func complain(jsonData: [String: Any], token: String) {
print(token)
request(complainURL, method: .post, parameters: jsonData, encoding: JSONEncoding.default, headers: ["Authorization": "Bearer \(token)"])
.responseString {(response) in
switch response.result {
case .success(let data):
if let error = JSON(data)["errors"].string {
self.delegate?.failureRequest(error: JSON(error).dictionaryObject!)
} else {
self.delegate?.updateRequest(rosemaryJSON: JSON(jsonData), byState: .complain)
}
case .failure(let error):
print("FAIL: \(error.localizedDescription)")
}
}
}
my JsonData
let param: [String: Any] = [
"details": "\(AlertTextField!.text!)",
"subject": "Complain",
"client_id": (EVTUser.user?.id!)!
]
my ORIGINAL code was ...
func complain(jsonData: [String: Any], token: String) {
print(token)
request(complainURL, method: .post, parameters: jsonData, encoding: JSONEncoding.default, headers: ["Authorization": "Bearer \(token)"])
.responseJSON {(response) in
switch response.result {
case .success(let data):
if let error = JSON(data)["errors"].string {
self.delegate?.failureRequest(error: JSON(error).dictionaryObject!)
} else {
self.delegate?.updateRequest(rosemaryJSON: JSON(jsonData), byState: .complain)
}
case .failure(let error):
print("FAIL: \(error.localizedDescription)")
}
}
}
i just change responseJSON to responseString and it works now! I got success..
Hope it will help someone.

Alamofire Swift convert

Hi I want to make a request to API, but when send, console show me
invalidURL
Alamofire.request("https://.../api/v1.8/set/order/?address=\(address)&email=\(email)&information=\(information)&name=\(name)&order=\(parameters)&password=\(password)&paymentType=\(paymentType)&phone=\(phone)&token=\(token)&userID=\(userID)&wihtRegistration=\(wihtRegistration)").validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result
{
case .failure(let error):
print(error)
case .success(let value):
print(value)
print("Request: \(response.request)")
}
}
How can I convert in Alamofire?
I have created this custom method. Call this by passing required parameter:-
Without JSON Encoding
func requestWithoutJSONEncoding(_ method: HTTPMethod
, _ URLString: String
, parameters: [String : AnyObject]? = [:]
, headers: [String : String]? = [:]
, completion:#escaping (Any?) -> Void
, failure: #escaping (Error?) -> Void) {
Alamofire.request(URLString, method: method, parameters: parameters, headers: headers)
.responseJSON { response in
switch response.result {
case .success:
completion(response.result.value!)
case .failure(let error):
failure(error)
}
}
}
With JSON Encoding
func request(_ method: HTTPMethod
, _ URLString: String
, parameters: [String : AnyObject]? = [:]
, headers: [String : String]? = [:]
, completion:#escaping (Any?) -> Void
, failure: #escaping (Error?) -> Void) {
Alamofire.request(URLString, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
switch response.result {
case .success:
completion(response.result.value!)
case .failure(let error):
failure(error)
}
}
}
Try this
let jsonObject = [["code": 404, "counts": 15]]
let json = JSON(jsonObject)
// Generate the string representation of the JSON value
let jsonString = json.rawString(.utf8)!
let params = ["name": name, "phone": phone, "address": address, "information": information, "email": email, "userID":userID, "wihtRegistration": wihtRegistration, "password": password, "token": token, "paymentType": paymentType, "order" : jsonString] as [String : Any]
Alamofire.request("http:...", method: .get, parameters: params)
.responseString { response in
#if DEBUG
(request!.url!.absoluteString)\n\(request!.httpBody.map { body in String(data: body, encoding: .utf8) ?? "" } ?? "")")
switch response.result {
case .success(let value):
print("Response with content \(value)")
case .failure(let error):
print("Response with error: \(error as NSError): \(response.data ?? Data())")
}
#endif
}

Alamofire 4 request to open weather

Working on my first Alamofire request and a code that is updated to Alamofire 4 . Can't get this Alamofire.request .responseJSON properly updated. I am looking at the Migration documentation: but not clever enough. Any suggestions how it should look?
let APIKey = "myAPIkey"
func retrieveCurrentWeatherAtLat(lat: CLLocationDegrees, lon: CLLocationDegrees,
block: (_ weatherCondition: WeatherCondition) -> Void) {
let url = "http://api.openweathermap.org/data/2.5/weather?APPID=\(APIKey)"
let params = ["lat": lat, "lon": lon]
// Send the request
Alamofire.request(url, method: .get, parameters: params)
.responseJSON { request, response, result in
switch result {
case .Success(let json):
let json = JSON(json)
block(weatherCondition: self.createWeatherConditionFronJson(json))
case .Failure(_, let error):
print("Error: \(error)")
}
}
}
maybe can help you
Alamofire.request(url, method: .get, parameters: params, encoding: JSONEncoding.default).responseJSON { (response) in
switch response.result {
case .Success(let json):
let json = JSON(json)
block(weatherCondition: self.createWeatherConditionFronJson(json))
case .Failure(_, let error):
print("Error: \(error)")
}
}
let APIKey = "YourApiKeyComesHere"
// Sending the request to Open Weather
func retrieveCurrentWeatherAtLat(lat: CLLocationDegrees, lon: CLLocationDegrees,
block: #escaping (_ weatherCondition: WeatherCondition) -> Void) {
let url = "https://api.openweathermap.org/data/2.5/weather?APPID=\(APIKey)"
let params = ["lat": lat, "lon": lon]
print("Sending request... \(url)")
let request = Alamofire.request(url, method: .get, parameters: params, encoding: URLEncoding(destination: .queryString)).responseJSON { (response) in
print("Got response from server: \(response)")
switch response.result {
case .success(let json):
let json = JSON(json)
block(self.createWeatherConditionFronJson(json: json))
print("Success: \(json)") //test
case .failure(let error):
print("Error: \(error)")
}
}
request.resume()
}

Custom made Creditcard Expiry Date field

I'm trying to make a POST API request using Alamofire 4.0 and Swift 3.0 but I'm having a tough time with it.
My Postman looks like this:
And using Basic Auth
I can't even get my code to compile for now and I've no idea why. This is my function:
func testCall(token:String, completionHandler: #escaping ((AnyObject?, Error?) -> Void)) {
let urlString = Constant.apiUrlString + Constant.apiPostOrderCard
print(urlString)
let parameters = ["test" : "test"]
Alamofire.request(urlString, method: .post, parameters: parameters, encoding: .JSON, headers: self.header).validate().responseJSON { (request, response, result) -> Void in
switch result {
case .Success(let value):
print(value)
completionHandler(value, nil);
break
case .Failure(let data, let error):
self.handleFailure(data, error: error, response: response, completionHandler: completionHandler)
break
}
}
What am I doing wrong?
Did you just migrate to Alamofire 4? There are couple of syntax changes, you need to read the migration guide when there is an version update.
Here is the updated code :)
func testCall(token:String, completionHandler: #escaping ((AnyObject?, Error?) -> Void)) {
let urlString = Constant.apiUrlString + Constant.apiPostOrderCard
let parameters : Parameters = ["test": "test"]
Alamofire.request(urlString, method: .post, parameters: parameters).validate().responseJSON { response in
if let status = response.response?.statusCode {
switch(status){
case 200:
if let result = response.result.value {
let JSON = result as! NSDictionary
// implement your logic here
completionHandler(value, nil);
}
break
case 400:
// implement your logic here
self.handleFailure(data, error: error, response: response, completionHandler: completionHandler)
break
default:
break
}
}
}
}
the Parameters is Alamofire's object, feel free to use its and the constructor had changed also.
Just replace your encoding: .JSON to encoding: JSONEncoding.default and ensure parameters has type Parameters:
Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: self.header).validate().responseJSON { response in
switch response.result {
case .success(let json): //do something
case .failure(let error): // do something
}
}