Alamofire: send parameter - ios

I want to post data as parameter like this:
{
"data":
[
{
"nik" : "lalaal"
}
]
}
How do I write to these parameters in Swift 3 using Alamofire?
i tried :
let parameter: Parameters = [
"data":[[
"nik" : self.nik,
"check_type" : "IN",
"tanggal" : "01-08-2017 18:22:00",
"long" : String(locationList[projectChoosen].long!),
"lat" : String(locationList[projectChoosen].lat!),
"id_loc" : locationList[projectChoosen].id_project,
"id_project" : nil,
"nama_project" : locationList[projectChoosen].nama_project,
"barcode" : "",
"foto": "",
"mime_type" : "image/jpeg"
]]
]

You can use below code.
let dicRequest: NSDictionary = ["userid" : "test", "password" : "test123"]
let postParams:NSDictionary = [
"data": dicRequest
]
let requestURL: String = String(format: "%#/Login", serverURL)
Alamofire.request(requestURL, method: .post, parameters: postParams as? [String : AnyObject], encoding: JSONEncoding.default, headers: [:])
.responseJSON { response in switch response.result {
case .success(let JSON):
print("response :-----> ",response)
case .failure(let error):
print("Request failed with error: \(error)")
}
}

You can create a Dictionary object first in this formate
{
"data":
[
{
"nik" : "lalaal"
}
]
}
After that you can convert this using NSJSONSerlisation to json string
And than post using Almofire.
let array: [[String: String]] = [["nik": "lalaal"]]
let data = try JSONSerialization.data(withJSONObject: array, options: JSONSerialization.WritingOptions.prettyPrinted)
let string = String(data: data, encoding: String.Encoding.utf8)
let postParam: [String: String] = ["data": string]
let _ = Alamofire.request(apiType.url!, method: apiType.type!,parameters: postParam, encoding: JSONEncoding.prettyPrinted, headers: nil).validate(statusCode: 200..<500).responseJSON { (response) in
}

Here is a sample request using Alamofire and posting a dictionary as parameters:
let dataArray: [[String: String]] = [["nik": "lalaal"]]
let param: [String: [Any]] = ["data": dataArray]
Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: nil).responseJSON { response in }

I use :
let dataIn: [String: String] = ["param1": "value1"]
let paramGo: [String: [String: String]] = ["data_title": dataIn]
Alamofire.request(url, method: .post, parameters: paramGo, encoding: JSONEncoding.default, headers: nil).responseJSON { response in }

Related

How to Arrangement array before send request to alamofire in swift

let request = NSMutableDictionary()
request.setDictionary([ "merchant_reference":getRandomMerchant, "merchant_identifier":"e54638eb", "access_code":"hRRVGXrIpHSYoH19Ebwt", "signature": base64Str, "service_command":"OTP_GENERATE", "language":"en", "payment_option":"VALU", "phone_number":"01008606003", "merchant_order_id":getRandomMerchant, "amount":getTotal, "currency":"EGP", "products":[ [ "product_name": getName, "product_price": getTotal, "product_category":getProductType ] ] ])
Alamofire.request(URLAPi.URL_Payment_Api ,
method : .post ,
parameters : (request as! Parameters) ,
encoding: JSONEncoding.default
).responseJSON { (response) in
debugPrint(response)
if response.result.isSuccess {
let jsonpayfortrequest : JSON = JSON(response.result.value!)
var resultsArray = jsonpayfortrequest.arrayValue
var sortedResults = resultsArray.sorted { $0.stringValue > $1.stringValue }
print(jsonpayfortrequest)
print(resultsArray)
print(sortedResults)
print(jsonpayfortrequest.sorted(by: {$0 > $1}))
let passobjectforrootclasspayfort = OTPGenrateModel(fromJson: jsonpayfortrequest)
print(passobjectforrootclasspayfort.transaction_id!)
SVProgressHUD.dismiss()
} else {
print("error connection") SVProgressHUD.dismiss()
}
}
Try this way, Hope, that will fixe your issue. If it doesn't, please reply
let parameters: [String: Any] = [
"merchant_reference":getRandomMerchant,
"merchant_identifier":"e54638eb",
"access_code":"hRRVGXrIpHSYoH19Ebwt",
"signature": base64Str,
"service_command":"OTP_GENERATE",
"language":"en",
"payment_option":"VALU",
"phone_number":"01008606003",
"merchant_order_id":getRandomMerchant,
"amount":getTotal,
"currency":"EGP",
"products": [
[
"product_name": getName,
"product_price": getTotal,
"product_category":getProductType
]
]
]
Alamofire.request(URLAPi.URL_Payment_Api , method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
// Insert your code here
}

Issue while sending array of dictionary in swift

I am creating array of dictionaries and then passing that in paramDictionary and sending to server but I get responseStatus code 422. I am using Alamofire 5.
Here is the structure of param which I have to send and it successfully working on postman but in app it is always fails
{"check_in": [{"check_in_at":"2020-02-26 03:23:44", "gps_coordinates":"3.1697998046875,101.61672197976593"},
{"check_in_at":"2020-02-26 03:23:45","gps_coordinates":"3.1697998046875,101.61672197976593"}]}
Here is my code
func postCheckInApi(viewController: UIViewController,
completion:#escaping (_ result:SuccessErrorData)->(),
errorHandler:#escaping (_ result:Error,_ statusCode:Int?)->()//error handler
) {
let url = KCheckin
let geoArr = Constant.getSearchLocationHistory() ?? [GeoTaggingEntity]()
var arr = [[String: String]]()
for i in geoArr{
let dict: [String : String] = ["gps_coordinates" : i.gps_coordinates ?? "", "check_in_at" : i.check_in_at]
arr.append(dict)
}
let parameterDictionary = ["check_in": arr] as [String : Any]
print(parameterDictionary)
let headers: HTTPHeaders = [
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": Constant.getBearerToken() ?? ""
]
AF.request(url, method: .post, parameters: parameterDictionary, headers: headers).responseData { response in
switch response.result{
case.success(let data):
do{
let jsonData = try JSONDecoder().decode(SuccessErrorData.self, from: data)
print("Success")
completion(jsonData)
}
catch{
//viewController.navigationController?.popToRootViewController(animated: true)
}
case .failure(let error):
print(error)
}
}
}
You can not add Array as parameter object to your paramDictionary. You need to covert your Array to json string and then add it to you paramDictionary.
For that use below Collection extension to convert your Array to Json String
extension Collection {
func json() -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: self, options: []) else {
return nil
}
return String(data: data, encoding: String.Encoding.utf8)
}
}
How To Use
let jsonStr = yourArray.json()
add this jsonStr to your paramDictionary

i got response error .. any idea ? using swift with Alamo fire i have to send post request as http body row

let parameters = ["order": ["line_items": [
["variant_id": 18055889387589, "quantity": 11]]]] as [String : Any]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.prettyPrinted, headers: headers).responseJSON { response in
switch response.result {
case .success:
print("response is ",response)
case .failure(let error):
print(0,"Error")
}
}
let parameters = ["order": ["line_items": [
["variant_id": 18055889387589, "quantity": 11]]]] as [String : Any]
let jsonData = try! JSONSerialization.data(withJSONObject: parameters)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)
i think the problem is your parametres try this one

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
}

Extra argument "method" in call. Alamofire

I'm using Alamofire to do a get request to Yelp api, i got my post request woking but my get request is not working what so ever, i have tried everything i read from other questions but still no solution. here are my codes.
This is my post request which is working.
class func getAccessToken() {
let parameters: Parameters = ["client_id": client_id, "client_secret": client_secret]
Alamofire.request("https://api.yelp.com/oauth2/token", method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).response {
response in
print("Request: \((response.request)!)")
print("Response: \((response.response)!)")
if let data = response.data {
let dict = try! JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
print("Access Token: \((dict["access_token"])!)")
self.accessToken = (dict["access_token"])! as? String
self.tokenType = (dict["token_type"])! as? String
}
}
}
This is my get request that i'm having trouble with.
class func getRestaurents(searchTerm: String) {
let parameters: Parameters = ["term": searchTerm, "location": "******"]
let headers: HTTPHeaders = [tokenType!: accessToken!]
Alamofire.request("https://api.yelp.com/v3/businesses/search", method: .get, parameters: Parameters, encoding: JSONEncoding.default, headers: headers).response {
response in
if let data = response.data {
let dict = try! JSONSerialization.jsonObject(with: data, options: [] as! [NSDictionary])
print(dict)
}
}
}
Thank you.
You are passing class Parameters instead of its object parameters.
Alamofire.request("https://api.yelp.com/v3/businesses/search", method: .get, parameters: Parameters, encoding: JSONEncoding.default, headers: headers).response {
Should be:
Alamofire.request("https://api.yelp.com/v3/businesses/search", method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers).response {

Resources