Why is Alamofire POST-Api-call not working? - swift

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.

Related

API working in Postman but giving error in Code

I am trying to call API in postman and its working fine, But If I am trying to call API in swift Alamofire, Its give me error-
My Code is-
func sendToServer(){
let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
let data: Parameters = ["SerialNo": "T8180399","Status":101]
Alamofire.request(urlString, method: .post, parameters: data,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
}
Error is-
The JSON value could not be converted to System.Collections.Generic.List`1[BreakBulkModels.Model.WebapiModels.DtoInventoryApi]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
Your API accepts as parameters an array of JSON objects but you are currently sending a JSON object:
{
"SerialNo": "T8180399",
"Status": 101
}
Because Parameters is a typealias to Dictionary<String, Any> (what you need is Array<Dictionary<String, Any>>) you have to do your parameter encoding yourself and then call request(_:) function of Alamofire passing your URLRequest:
do {
let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
let url = try urlString.asURL()
var request = URLRequest(url: url)
let data = [["SerialNo": "T8180399", "Status": 101]]
request = try JSONEncoding.default.encode(request, withJSONObject: data)
Alamofire.request(request).responseJSON { response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
} catch {
print(error)
}
Edit: With Alamofire v5 there is a more elegant way by using Encodable protocol:
struct BarCode: Encodable {
var SerialNo: String
var Status: Int
}
func sendToServer(){
let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
let data = [BarCode(SerialNo: "T8180399", Status: 101)]
AF.request(
urlString,
method: .post,
parameters: data,
encoder: JSONParameterEncoder.default
).responseJSON { response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
}

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

Unexpected non-void return value in void function (Swift 3) [duplicate]

This question already has answers here:
How to return value from Alamofire
(5 answers)
Closed 5 years ago.
func postUser(username: String, pass: String) -> Bool {
Alamofire.request("https://someAPI.com/auth/login", method: .post, parameters: ["email": contact, "password": pass], encoding: URLEncoding.default, headers: ["Accept":"application/json"]).responseJSON { (response) in
switch(response.result) {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
print(json["data"]["result"])
return true
case .failure(let error):
print(error)
return false
}
}
}
If you are calling an async method like Alamofire.request, then you need notify when this async method is over with closures
Try with this
func postUser(username: String, pass: String, finishedClosured:#escaping ((Bool)->Void)) {
Alamofire.request("https://someAPI.com/auth/login", method: .post, parameters: ["email": contact, "password": pass], encoding: URLEncoding.default, headers: ["Accept":"application/json"]).responseJSON { (response) in
switch(response.result) {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
print(json["data"]["result"])
finishedClosured(true)
case .failure(let error):
print(error)
finishedClosured(false)
}
}
}
Use it
self.postUser(username: "your UserName", pass: "Your Pass") { (result) in
if(result){
debugPrint("All is fine")
}else{
debugPrint("All is wrong")
}
}
You should not return true or false from this method, since this the asynchronous network call, simply use call backs to get your data outside
func postUser(username: String, pass: String callback: #escaping (Bool) -> Void){
Alamofire.request("https://someAPI.com/auth/login", method: .post, parameters: ["email": contact, "password": pass], encoding: URLEncoding.default, headers: ["Accept":"application/json"]).responseJSON { (response) in
switch(response.result) {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
print(json["data"]["result"])
callback(true) //using this you can send back the data
case .failure(let error):
print(error)
callback(false)
}
}
//here you can return true or false but I dont think you should
}