Alamofire request with Parameters - ios

I have this url : https://eee.com/geo?lat=10.2&lng=10.2
And i want to pass 2 parameters instead of 10.2. How should Alamofire request looks ?

if Request method is Get,May be
Alamofire.request("https://eee.com/geo?lat=10.2&lng=10.2").responseData { (dataResponse) in
if let data = dataResponse.data {
print(String(data: data, encoding: .utf8) ?? "")
}
}
if Request method is Post,May be
Alamofire.request("https://eee.com/geo", method: .post, parameters: [ "lat" :10.2,"lng":10.2 ] ).responseData { (dataResponse) in
if let data = dataResponse.data {
print(String(data: data, encoding: .utf8) ?? "")
}
}

Related

Alamofire post request with body

I am trying to send POST HTTP request with body using Alamofire and would appreciate any help.
My body:
{"data":{"gym":{"country":"USA","city":"San Diego","id":1}}}
Should I do something like this?
let parameters: [String: Any] = [ "data": [
"gym": [
"country":"USA",
"city":"San Diego",
"id":1
]]]
Alamofire.request(URL, method: .post, parameters: parameters, headers: headers())
.responseJSON { response in
print(response)
}
If you wish to send the parameters in json format use encoding as JSONEncoding. So add parameter for encoding in request as follows:
Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers())
.responseJSON { response in
print(response)
}
Hope it helps...
Try this method to convert your json string to dictionary
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"data\":{\"gym\":{\"country\":\"USA\",\"city\":\"San Diego\",\"id\":1}}}"
let dict = convertToDictionary(text: str)
and send dictionary as a param in your request.
Alamofire.request(URL, method: .post, parameters: dict, headers: headers())
.responseJSON { response in
print(response)
}
ref : How to convert a JSON string to a dictionary?
What I think is that you should try and prepare your dictionary in the this format:
var gym = [String:Any]()
gym["country"] = "USA"
gym["city"] = "San"
var data = [[String:Any]]()
data.append(gym)
var metaData = [String:Any]()
metaData["data"] = data
Your parameters is wrong...
let parameters: [String: Any] = { "data":
{
"gym": {
"country":"USA",
"city":"San Diego",
"id":1
}
}
}
Alamofire.request(<YOUR-URL>,
method: .post,
parameters: parameters,
encoding: URLEncoding(destination: .queryString),
headers: <YOUR-HEADER>
).validate().responseString { response in
switch response.result {
case .success:
debugPrint("Good to go.")
debugPrint(response)
case .failure:
let errMsg = String(data: response.data!, encoding: String.Encoding.utf8)!
debugPrint(errMsg)
debugPrint(response)
}
}
Hope this help. BTW, in Alamofire 5, debugPrint(response) can print out response.data directly.
You can use the httpBody property of URLRequest along with Alamofire Session request:
var req = try? URLRequest(url: url, method: method, headers: headers)
req?.httpBody = someJson
Alamofire.Session(configuration: .default).request(req!).validate().response { response in
// Handle the response
}

JSON data not parsing using with Alamofire in swift3

I have to parse json using alamofire
before am using json session its working fine getting data from the json. now am try to parse json using alamofire.
this is the code parse the json using json, this code working fine
func auth(_ email:String,password:String) {
var request = URLRequest(url:AppConstants.apiURLWithPathComponents("usersignin"))
let session = URLSession.shared
request.httpMethod = "POST"
let bodyData = "email=\(email)&passCode=\(password)&deviceType=iOS&deviceId=\(deviceToken)"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
do {
if data != nil {
if let jsonData = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
errorCode = String(describing: jsonData["errorCode"]!)
msg = jsonData["msg"] as! String
print(errorCode)
print(jsonData)
if(errorCode == "1"){
DispatchQueue.main.async(execute: {
self.activityIndicator.stopAnimating()
})
} else {
self.name = jsonData.value(forKey: "name") as! String
if let kidsURLDetails = jsonData["kidsURLDetails"] as? NSArray {
for i in 0 ..< kidsURLDetails.count {
if kidsURLDetails[i] is NSDictionary {
let url = kidsURLDetails[i] as? NSDictionary
self.urls.append((url?["url"]) as! String)
}
}
}
self.serverURL = self.urls.joined(separator: ",")
print("ServerURL \(self.serverURL)")
let prefs:UserDefaults = UserDefaults.standard
prefs.setValue(self.name, forKey: "NAME")
DispatchQueue.main.async(execute: {
UIApplication.shared.endIgnoringInteractionEvents()
let controllerId = "NavID"
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initViewController: UIViewController = storyboard.instantiateViewController(withIdentifier: controllerId) as UIViewController
self.present(initViewController, animated: true, completion: nil)
})
}
}
} else {
}
} catch let err as NSError {
print("JSON Error \(err)")
}
})
task.resume()
}
in above code I used post method with passing parameters, when I am trying post method with parameter passing in almofire am getting error "Extra argument 'method' in call", username and password coming from textfield so after enter the email and password I have pass the parameters using post method.
this is the code I will implemented in to alamofire json parse
var request = URLRequest(url:AppConstants.apiURLWithPathComponents("usersignin"))
let bodyData = "email=\(username)&passCode=\(passcode)&deviceType=iOS&deviceId=123456"
let deviceId = "1234"
let params: [String: Any] = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
Alamofire.request(request, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil)
.responseJSON { response in
print(response.result.value as Any) }
if I can try this code working
Alamofire.request("http://www.kids.com/rk/api/usersignin?email=demo#kidsapp.com&passCode=123456&deviceType=&deviceId=", method: .post, parameters: nil, encoding: JSONEncoding.default, headers: nil)
.responseJSON { response in
print(response.result.value as Any) }
how can I parse the json post method passing parameters using alamofire. where I did mistake pls help me
You are passing wrong type in 1 param in call it should be URLConvertible(string or URL) not URLRequest. try below code.
let params: [String: Any] = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
let url = URL(string: "http://www.kids.com/rk/api/usersignin")!
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil)
.responseJSON { response in
}
____________Edit___________
here header is post request headers(if any) or nil
let params: [String: Any] = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
let urlString = "http://www.kids.com/rk/api/usersignin"
guard let url = URL(string: urlString), var request = try? URLRequest(url: url, method: .post, headers: header) else{
//
return
}
request.httpBody = params.map{ "\($0)=\($1)" }.joined(separator: "&").data(using: .utf8)
Alamofire.request(request).responseJSON { response in
}
If you need to send the parameters in url with post request you should use URLEncoding.default encoding rather than JSONEncoding.default. JSONEncoding is used when you need to send JSON data as body with content type application/json.
Change your code like:
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { response in
print(response.result.value as Any)
}
Or you can remove encoding parameter as URLEncoding is the default encoding of Alamofire.
// URL
let urlString = “URL_Here”
var params = [String: Any]()
//Contruct your params
params = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
// Request
Alamofire.request(urlString, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.responseJSON { response in
if (response.result.error == nil) {
let value = response.result.value
print(value)
}
else {
let errorString = response.result.error
print(errorString)
}
}

How to send form-data body with Alamofire [duplicate]

This question already has answers here:
Send POST parameters with MultipartFormData using Alamofire, in iOS Swift
(13 answers)
Closed 5 years ago.
I want to make a request wit Alamofire like this:
postman request
As you can see, i have a parameter called "data" and its value is a Json,
How can i do that using Alamofire?
I have tried with parameters, but doesnt wotk
Alamofire.request(urlservice, method: .post, parameters: ["data": parameters], encoding: JSONEncoding.default, headers: nil).responseJSON { response in
Any suggestions?
UPDATE
Here is my code
var arrayProducts = [[String: String]]()
let product: [String: String] = ["qty": self.txtQty.text!, "precio": self.productPrice, "product_id": self.productId]
arrayProducts.append(product)
let parameters = [
"products": arrayProducts,
"address": self.userInfo["userAddress"]!,
"latitude": "6.157738",
"longitude": "-75.6144665",
"id": 1,
"name": self.userInfo["userName"]!,
"cellphone": self.userInfo["userPhone"]!,
"emei": "23456resdfty"
] as [String : Any]
Alamofire.request(urlservice, method: .post, parameters: ["data": parameters], encoding: JSONEncoding.default, headers: nil).responseJSON { response in
when you have an Any Data as paremeter, you should sent the URLRequest to Alamofire, it supports Any as body
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: [])
Alamofire.request(request)
.responseString { (response) in
// to do anything
}
Here is an example 4 you, the CURL statement an example of what it is doing.
Note token referenced here is a shared secret, obviously not stuff to post to SO :) bags of print statements in here so that you can see what going on/wrong :)
func files_download(sourcePath: String) {
// curl -X POST https://content.dropboxapi.com/2/files/download
// --header "Authorization: Bearer ab-XXX"
// --header "Dropbox-API-Arg: {\"path\": \"/acme101/acme1/acme.png\"}"
var headers:HTTPHeaders!
let subPart: Dictionary = ["path":sourcePath]
do {
let data = try JSONSerialization.data(withJSONObject: subPart, options: [])
let dataString = String(data: data, encoding: .utf8)
headers = ["Authorization": "Bearer " + token, "Dropbox-API-Arg": dataString!]
} catch {
print("Oh fudge")
}
Alamofire.request("https://content.dropboxapi.com/2/files/download", method: .post, encoding: JSONEncoding.init(options: []), headers: headers).responseData(completionHandler: {feedback in
guard feedback.result.value != nil else {
print("Error: did not receive data", //rint("request \(request) feedback \(feedback)"))
return
}
guard feedback.result.error == nil else {
print("error calling POST on list_folder")
print(feedback.result.error)
return
}
if let JSON = feedback.result.value {
print("JSON: \(JSON)")
let dataString = String(data: JSON, encoding: .utf8)
print("JSON: \(JSON) \(String(describing: dataString))")
}
if let IMAGE = feedback.result.value {
print("downloaded \(sourcePath) \(sharedDataAccess.currentSN)")
sharedDataAccess.fnData(index2seek: sharedDataAccess.currentSN, fnData: feedback.result.value! as Data)
NotificationCenter.default.post(name: Notification.Name("previewPane"), object: nil, userInfo: nil)
}
})
}

Alamofire POST request not working

let requestDictionary : [String: AnyObject] = [
"sm_username" : name as AnyObject,
"sm_password" : pass as AnyObject
]
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Content-Type": "application/x-www-form-urlencoded",
"Krikor": "Krikor"
]
Alamofire.request(baseURL+"login", method: .post, parameters: requestDictionary, encoding: JSONEncoding(options: []),headers: headers
).responseJSON{ response in
debugPrint(response)
print("krirkrkdkd")
print(response)
}
So basically, the headers are not being passed. Neither encoded parameters. Why? And how to fix?
Kiikor,
Here is a working example of a alamofire request in swift, including the encoding.
func files_download(sourcePath: String) {
let defaults = UserDefaults.standard
if let name = defaults.string(forKey: "dropBoxAuth")
{
token2Save = name
}
var headers:HTTPHeaders!
let subPart: Dictionary = ["path":sourcePath]
do {
let data = try JSONSerialization.data(withJSONObject: subPart, options: [])
let dataString = String(data: data, encoding: .utf8)
headers = ["Authorization": "Bearer " + token2Save, "Dropbox-API-Arg": dataString!]
} catch {
print("error")
}
Alamofire.request("https://content.dropboxapi.com/2/files/download", method: .post, encoding: JSONEncoding.init(options: []), headers: headers).responseData(completionHandler: {feedback in
guard feedback.result.value != nil else {
print("Error: did not receive data", print("request \(request) feedback \(feedback)"))
return
}
guard feedback.result.error == nil else {
print("error calling POST on list_folder")
print(feedback.result.error)
return
}
if let JSON = feedback.result.value {
let dataString = String(data: JSON, encoding: .utf8)
}
if let IMAGE = feedback.result.value {
sharedDataAccess.fnData(index2seek: 0, fnData: feedback.result.value! as Data)
NotificationCenter.default.post(name: Notification.Name("nextACtion"), object: nil, userInfo: nil)
}
})

URL Encode Alamofire GET params with SwiftyJSON

I am trying to have Alamofire send the following parameter in a GET request but it's sending gibberish:
filters={"$and":[{"name":{"$bw":"duke"},"country":"gb"}]}
//www.example.com/example?filters={"$and":[{"name":{"$bw":"duke"},"country":"gb"}]}
//Obviously URL encoded
This is my code:
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
print(json)
outputs
{
"$and" : [
{
"name" : {
"$bw" : "duke"
},
"country" : "gb"
}
]
}
This is my params request:
let params = ["filters" : json.rawValue, "limit":"1", "KEY":"my_key"]
This is what AlamoFire is sending:
KEY=my_key&
filters[$and][][country]=gb&
filters[$and][][name][$bw]=duke&
limit=1
As you can see the filter parameter is a complete mess. What am I doing wrong?
By default Alamofire encodes the parameters using Parameter List in the POST body. Try changing the encoding to JSON. This way Alamofire will serialize the dictionary as a JSON string as you expect:
let parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
Or using your code:
let string = "duke"
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
let params = ["filters" : json.rawValue, "limit":"1", "KEY":"my_key"]
Alamofire.request(.POST, "http://httpbin.org/post", parameters: params, encoding: .JSON)
.responseString(encoding: NSUTF8StringEncoding) { request, response, content, error in
NSLog("Request: %# - %#\n%#", request.HTTPMethod!, request.URL!, request.HTTPBody.map { body in NSString(data: body, encoding: NSUTF8StringEncoding) ?? "" } ?? "")
if let response = response {
NSLog("Response: %#\n%#", response, content ?? "")
}
}
Gets the output:
Request: POST - http://httpbin.org/post
{"filters":{"$and":[{"name":{"$bw":"duke"},"country":"gb"}]},"limit":"1","KEY":"my_key"}
EDIT: URL-Encoded JSON in the GET parameters
If you want to send a URL-Encoded JSON in the GET parameters you have to generate first the JSON string and then pass it as a string in your parameters dictionary:
SWIFT 1
let string = "duke"
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
// Generate the string representation of the JSON value
let jsonString = json.rawString(encoding: NSUTF8StringEncoding, options: nil)!
let params = ["filters" : jsonString, "limit": "1", "KEY": "my_key"]
Alamofire.request(.GET, "http://httpbin.org/post", parameters: params)
.responseString(encoding: NSUTF8StringEncoding) { request, response, content, error in
NSLog("Request: %# - %#\n%#", request.HTTPMethod!, request.URL!, request.HTTPBody.map { body in NSString(data: body, encoding: NSUTF8StringEncoding) ?? "" } ?? "")
if let response = response {
NSLog("Response: %#\n%#", response, content ?? "")
}
}
SWIFT 2
let string = "duke"
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
// Generate the string representation of the JSON value
let jsonString = json.rawString(NSUTF8StringEncoding)!
let params = ["filters" : jsonString, "limit": "1", "KEY": "my_key"]
Alamofire.request(.GET, "http://httpbin.org/post", parameters: params)
.responseString(encoding: NSUTF8StringEncoding) { request, response, result in
NSLog("Request: %# - %#\n%#", request!.HTTPMethod!, request!.URL!, request!.HTTPBody.map { body in NSString(data: body, encoding: NSUTF8StringEncoding) ?? "" } ?? "")
switch result {
case .Success(let value):
NSLog("Response with content: %#", value)
case .Failure(let data, _):
NSLog("Response with error: %#", data ?? NSData())
}
}
SWIFT 3 and Alamofire 4.0
let string = "duke"
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
// Generate the string representation of the JSON value
let jsonString = json.rawString(.utf8)!
let params = ["filters" : jsonString, "limit": "1", "KEY": "my_key"]
Alamofire.request("http://httpbin.org/post", method: .get, parameters: params)
.responseString { response in
#if DEBUG
let request = response.request
NSLog("Request: \(request!.httpMethod!) - \(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
}
This generates a GET request with the following URL:
http://httpbin.org/post?KEY=my_key&filters=%7B%22%24and%22%3A%5B%7B%22name%22%3A%7B%22%24bw%22%3A%22duke%22%7D%2C%22country%22%3A%22gb%22%7D%5D%7D&limit=1
That URL-Decoded is:
http://httpbin.org/post?KEY=my_key&filters={"$and":[{"name":{"$bw":"duke"},"country":"gb"}]}&limit=1

Resources