Alamofire Swift convert - swift

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
}

Related

Why is Alamofire POST-Api-call not working?

The POST-parameters are not passed. Why?
Is there another possibility to make POST-API-Calls?
let parameters: [String: String] = ["username" : "test", "password" : "test"]
Alamofire.request("http://192.168.2.117/evk-ph/api/verify_user.api.php",
method: .post,
parameters: parameters,
encoding: JSONEncoding.default,
headers: nil).responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
print(error)
}
}
Here is a code that maybe work for use just do a simple changes in your code
func postJSON() {
let param = ["username":tFusername.text!,"password":tFpassword.text!] as NSDictionary //GET TEXTFIELD VALUE
let url = "YOUR URL HERE"
Alamofire.request(url, method: .post, parameters: (param as! Parameters), encoding: JSONEncoding.default).responseJSON { response in
switch response.result{
case .success(let json):
print(json)
DispatchQueue.main.async {
print(param)
//HANDLE YOUR CODE HERE
}
case .failure(let error):
print(error)
}
}
Use this Function in your viewDidLoad() or as you required.

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

Alamofire Contextual type anyobject cannot be used with dictionary literal

I am invoking a POST request where I provide the params, url from another method and get the error:
Contextual type anyobject cannot be used with dictionary literal
This is how I invoke and get the error here:
API.sharedInstance.post(NSURL(string: baseURL)!, params: ["name": val, "owner": "John"])
Here is my Alamofire code:
func post(url: NSURL, params: AnyObject) {
Alamofire.request(.POST, baseURL, parameters: params as! [String : AnyObject])
.validate()
.responseJSON { response in
switch response.result {
case .Success:
print("Validation Successful")
print("response = \(response)")
case .Failure(let error):
print(error)
}
}
}
try to replace
func post(url: NSURL, params: AnyObject) {
Alamofire.request(.POST, baseURL, parameters: params as! [String : AnyObject])
with
func post(url: NSURL, params: [String : AnyObject]) {
Alamofire.request(.POST, baseURL, parameters: params)

Alamofire get response from POST

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