Alamofire: how to handle and classify errors? - swift

One example for Alamofire is given as:
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)
}
}
How can I handle errors like "network in down", "404", "server not found", to give informative excuses to the user for why their stuff isn't loading?

You can get http status code and handler it like this:
Alamofire.request(.GET, USERS_URL, headers: headers, encoding: .JSON)
.responseJSON { response in
debugPrint(response)
switch response.result {
case .Success(let data):
if response.response!.statusCode == 200 {
//do things
}else if response.response!.statusCode == 401 {
//do things
}
case .Failure(let error):
print("Request failed with error: \(error)")
}
}

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

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 response parse

I am using Alamofire, how parsing results with UTF-8?
I have try utf8text["parameter"] but not working
Alamofire.request("http://*******.com/alamofire.php", method: .post, parameters: parameters).validate().responseJSON { response in
switch response.result {
case .success:
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
case .failure(let error):
print(error)
}
}
I am using Alamofire 4.7
swift 4
xcode 9.2
It should be possible to use the response string instead of decoding the data to UTF-8:
Alamofire.request("http://*******.com/alamofire.php", method: .post, parameters: parameters).validate().responseString { response in
switch response.result {
case .success:
print(response.value)
case .failure(let error):
print(error)
}
}
Does this print the correct result?

Alamofire GET request parameters

When send GET request with parameters, url encoded in a different way
http://someurl/search-ads?attributes[elevator]=1&attributes[ranges][square][]=20.0&attributes[ranges][square][]=170.0&cities[]=somecity&currency=kgs&has_images=0&not_first_floor=1&not_last_floor=1&order_type=sale&rating__gte=5&rating__lte=10000&specialty=2
but it should be
http://someurl/search-ads?specialty=7&order_type=sale&attributes={"ranges":"{\"square\":[2450,8190]}"}&cities=somecity&page=1
Is there any settings to change, to force Alamofire to encode in second way?
I am using Alamofire 3
Here is my method
func makeSearch(search: GeneralSearch) {
let request = Alamofire.request(.GET, SearchURL, parameters: Mapper().toJSON(search), encoding: .URL).validate().responseJSON {
response in
switch response.result {
case .Success:
if let responseValue = response.result.value {
print(responseValue)
}
break
case .Failure(let error):
print("Error: " + error.localizedDescription)
break
}
}
}