Alamofire post request with body - ios

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
}

Related

Post method request Alamofire (responseObject)

I want to create Alamofire POST request
but I get failure response , I dont know the error in mapping object or in the request
func loginUser() {
let URL = ..... + "/Login"
let params2 = "{\"MobileNumber\":\"\(MobileNumber.text!)\"}"
Alamofire.request(URL, method: .post, parameters: [:], encoding: params2, headers: [
"Content-Type": "application/json"]).responseObject { (response: DataResponse<Login>) in
if(response.result.isFailure){
print ("failure")
print (response.result.description)
return
}
else{
print(response.result) // result of response serialization
self.LoginUser = response.result.value
}
}
It looks like you are setting encoding property of the request method to your param2 variable.
Try setting parameter to param2 and update encoding to use .default:
Alamofire.request(URL, method: .post, parameters: param2, encoding: .default, headers: ...
You did not pass proper values into required fields. Use the corrected version below hope it helps
func loginUser() {
let URL = ..... + "/Login"
let params2: [String: Any] = ["MobileNumber" : "\(MobileNumber.text!)"]"
let header = ["Content-Type": "application/json"]
Alamofire.request(URL, method: .post, parameters: params2, encoding: JSONEncoding.default, headers: header).responseObject { (response: DataResponse<Login>) in
if(response.result.isFailure){
print ("failure")
print (response.result.description)
return
}
else{
print(response.result) // result of response serialization
self.LoginUser = response.result.value
}
}

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: send parameter

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 }

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

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