Alamofire GET request parameters - swift

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

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

Can't access Alamofire Request body

I'm facing a problem while requesting from server, everything was fine
suddenly the Alamofire.request can't access responseJSON and can't access the body of the function and it returns , what I have to do?
I'm using multi Alamofire request in the navigationController but after two or three requests this happens!
I'm really in trouble please help me!
this code can't execute
let group = DispatchGroup()
group.enter()
Alamofire.request(url, method: .get, parameters: nil,
encoding:
JSONEncoding.default, headers: header as? HTTPHeaders)
.responseJSON { (response) in
if response.result.isSuccess{
if let response = response.result.value {
let json = JSON(response)
self.updateAnswers(json: json)
print(json.arrayValue)
group.leave()
}
}
}
If it’s not successful, you should dive in and take a look at the error that was returned. You might even want to look at the body of the response (if its a development server, it might provide some useful error messages in the body of the response).
let group = DispatchGroup()
group.enter()
Alamofire.request(...)
.responseJSON { response in
defer { group.leave() }
switch response.result {
case .failure(let error):
print(error)
print(response.response ?? "no HTTPURLResponse")
if let data = response.data {
if let string = String(data: data, encoding: .utf8) {
print(string)
} else {
print(data as NSData)
}
} else {
print("no data")
}
case .success(let json):
print(json)
}
}
By the way, I’d suggest moving the leave call outside of any if/switch statement because you want to make sure your dispatch group is satisfied regardless of whether it was successful or not.
But, bottom line, you won’t be able to diagnose the problem until you start to look at precisely what error was returned.

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

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?

Pass token with post request using Alamofire

I'm new to iOS and I would like some direction on why my code isn't working. I'm trying to make a call to a url and pass a token and get the response. My response is coming back with a 404 status code.
let reverse = ["token": "831b21c47a7f7daee7d6e4e3fa11deaa"]
let url = "http://challenge.com"
Alamofire.request(url, parameters: reverse).responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Try bellow code:
Alamofire.request(url, method: .get, parameters: reverse, encoding: JSONEncoding.default).responseString { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Try this Code:
This code is also handle the error when response will be the blank and also the Internet connection is disable.
func apiCall(params : [String:AnyObject],block:([String:AnyObject]->Void)?) {
if Reachability.isConnectedToNetwork(){
Alamofire.request(.POST, URL, parameters: params, encoding: .JSON, headers: nil).responseJSON{
response in
let data = response.result.value
if data == nil{
if response.result.error?.code == -1005 {
print(response.result.error?.localizedDescription)
}
else{
switch response.result {
case .Success:
block!(data as! [String:AnyObject])
case .Failure(let error):
print(error)
}
}
}
}
else{
print(NO_NETWORK)
}
}