Why is the code below not working? Maybe something wrong with parameter?
let key = "LLLLLXXXXXXZZZZZZKEY"
let nonce = 3
let parameters: Parameters = ["api_key": key, "nonce": nonce]
let data = "method=getInfo&nonce=" + String(nonce)
let sign = generateHMAC(key: key, data: data)
let headers: HTTPHeaders = [
"Content-Type" : "application/x-www-form-urlencoded",
"Key": "LLLLLXXXXXXZZZZZZKEY",
"Sign": sign,
]
Alamofire.request("https://bitye.com/api/1/bid", method: .post, parameters: parameters, headers: headers).response { response in
debugPrint(response.response)
}
That's because your request is incorrect. According to it's API it should be:
let headers: HTTPHeaders = [
"Content-Type" : "application/json"
]
let parameters: Parameters = [
"api_key" : "API_KEY",
"base" : "BTC",
"counter" : "USD",
"amount" : "1",
"price" : "4000.11111"
]
let bidUrl = "https://bityep.com/api/1/bid"
Alamofire.request(bidUrl, method: .post, parameters: parameters, headers: headers).response { response in
debugPrint(response.response)
}
Related
I have a JSON file with this struct:
{
"example": {
"projects": [
{ "projectname" : "abc",
"date" : "20200930",}
{ "projectname" : "bac",
"date" : "20200803",}
]
}
}
I want to update first projectname, but not the date connected to it. But the AF.request method give me back error 400 (Invalid JSON body passed.)
let user = "username"
let password = "password"
let params = ["example":
["projects":
["projectname": "New Name"]
]
]
let credentialData = "\(user):\(password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let base64Credentials = credentialData.base64EncodedString()
let headers : HTTPHeaders = [
"Authorization": "Basic \(base64Credentials)",
"Accept": "application/json",
"Content-Type": "application/json" ]
AF.request("https://example.com/api", method: .put, parameters: params, headers: headers).responseJSON { AFdata in
do {
guard let jsonObject = try JSONSerialization.jsonObject(with: AFdata.data!) as? [String: Any] else {
print("Error: Cannot convert data to JSON object")
return
}
guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else {
print("Error: Cannot convert JSON object to Pretty JSON data")
return
}
guard let prettyPrintedJson = String(data: prettyJsonData, encoding: .utf8) else {
print("Error: Could print JSON in String")
return
}
print(prettyPrintedJson)
} catch {
print("Error: Trying to convert JSON data to string")
return
}
}
Thanks for your help!
I believe you are missing the encoder parameter in you request:
AF.request("https://example.com/api", method: .put, parameters: params, headers: headers, encoder: JSONParameterEncoder.default).responseJSON { AFdata in
Without it Alamofire cannot know that your parameters should be encoded as JSON.
I'm having difficulty with a parameter which contains a Json array using Alamofire
Here is a string of my Json:
"[{\"id\":546836102,\"count\":1},{\"id\":216479424,\"count\":1}]"
Here is my code where I make the request:
let data = (params["cart"] as! String).data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .fragmentsAllowed) as? [Dictionary<String, Int>] {
let parameters: Parameters = [
"address_id": params["address_id"] as! Int,
"delivery_day": params["delivery_day"] as! String,
"delivery_hour": params["delivery_hour"] as! Int,
"cart": jsonArray,
"via": params["via"] as! String
]
Alamofire.request(Global.baseURL + "orders/finish", method: .post, parameters: parameters, encoding: URLEncoding.default, headers: header)
.responseSwiftyJSON {
Printing out my parameters
["cart": [["id": 546836102, "count": 1], ["count": 1, "id": 216479424]], "address_id": 641589205, "delivery_day": "1399-01-20", "delivery_hour": 21, "via": "ios"]
Backend must receive the cart as below:
[
{
"id": 123456,
"count": 2
},
{
"id": 654321,
"count": 3
}
]
But instead it gets the data like this:
{
"delivery_hour" : "21",
"delivery_day" : "1399-01-20",
"cart" : [
{
"count" : "1"
},
{
"id" : "546836102"
},
{
"count" : "1"
},
{
"id" : "216479424"
}
],
"via" : "ios",
"address_id" : "641589205"
}
I have tried JSONEncoding and URLEncoding options by Alamofire but nothing seems to work and this is the closest I've gotten to the API template so far.
What am I doing so wrong here?
// MARK: - Update
So I updated to the latest version of Alamofire and still no good results :(
Here is the code:
let payload = MyParameters(address_id: 641589205, delivery_day: "1399-01-21", delivery_hour: 21, cart: items, via: "ios")
AF.request(url, method: .post, parameters: payload, encoder: JSONParameterEncoder.default, headers: .init(header), interceptor: nil).response { dataResponse in
switch dataResponse.result {
case .success(let value):
if dataResponse.response?.statusCode == 200 {
let json = JSON(value!)
completionHandler(json, nil)
} else {
print(dataResponse.response?.statusCode ?? -1)
}
case .failure(let error):
print(error)
completionHandler(nil, error.localizedDescription)
}
}
My payload looks exactly what I want it to be
{
"cart" : [
{
"count" : 1,
"id" : 546836102
},
{
"count" : 1,
"id" : 216479424
}
],
"via" : "ios",
"address_id" : 641589205,
"delivery_day" : "1399-01-21",
"delivery_hour" : 21
}
But then again the endpoint receives this:
{
"{\"delivery_day\":\"1399-01-21\",\"address_id\":641589205,\"delivery_hour\":21,\"cart\":" : {
"{\"id\":546836102,\"count\":1},{\"id\":216479424,\"count\":1}" : null
}
}
Using Alamofire 4, you can't send arrays using the method you've shown, as the Parameters type is [String: Any]. You're also not using the correct ParameterEncoding. If you want to send a JSON body, you need to use the JSONEncoding. What you can do is manually serialize the array into a URLRequest and make that request using Alamofire.
Additionally, if you update to Alamofire 5, Encodable parameters are now supported, so you if you can define your parameters as an Encodable type, sending them would be as easy as passing an array.
AF.request(..., parameters: [some, encodable, values], encoder: JSONEncoder.default)...
I need to do this in my project:
multiple values in multiple array common key for parameter
Some links that have the same question but no exact answers, I always see posts that have answers like use a custom encoding and that's it.
https://github.com/Alamofire/Alamofire/issues/570
i have 4 array :
var imagesArray: [UIImage] = [], var DayOpreation: [String] = [],varDayOffStart: [String] = [], var DayOffEnd: [String] = []
and this my code :
let parameters : Parameters = [
"about": self.descriptionLabel.text!,
"address" : addressLabel.text!,
"country" : "1",
"state": "1",
"city" : "1",
"postcode" : self.postalCode.text!,
"policies": self.policiesLabel.text,
"longitude" : "",
"latitude" : "",
"available_24hours": "0",
"open_hour" : "09:00",
"closed_hour" : "18:00",
"operating_days[0]": "Senin",
"days_off[0][start]" : "2019-10-10",
"days_off[0][end]" : "2019-10-15",
]
let token = UserDefaults.standard.string(forKey: UserDefaultConstant.ACCESS_TOKEN)
let headers = ["key": "\(token!)"
]
let ImageData = UIImageView()
ImageData.image = UIImage(named: "rectangle-1")
let imgData = UIImagePNGRepresentation(ImageData.image!)!
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "photo_profile[0]",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
},
to:"\(Endpoints.BASE)\(Endpoints.UPDATE_VENDOR)",
method: .post,
headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if let data = response.data {
guard let json = try? JSON(data: data) else { return }
let messageRoom = json["message"].string
print("listOfficialRoom== ",json)
}
}
case .failure(let encodingError):
print(encodingError)
}
})
Use Paramaters in Alamofire, something like this
let daysOff = [String: Any]() // array of dictionaries for days off
for (i, day) in days.enumerated() {
let dayOff: Parameters = [
"start": day.start,
"end": day.end
]
daysOff["\(i)"] = dayOff
}
let parameters: Parameters = [
"open_hour": "...",
"closed_hour": "...",
"days_off": daysOff
]
i want to post array of dictionaries in alamofire, but some how it is not posting.i can use many ways but still not find the proper answer on it. Showing error "Extra argument 'method' in call" . Here is my code.
let userToken: HTTPHeaders = [
"Content-Type": "application/json"
]
let parm = [
[
"EmployeeID": id,
"Longitude": longitude,
"Latitude": latitude,
"GeoTime": dateString,
"UserToken": "g98XQdy8B}rQ7?Q"
]
]
postAttandance(apiUrl: postAttandanceURL, parameter: parm , tiket: userToken){
(done) -> Void in
if done{
}
}
func postAttandance(apiUrl : String , parameter : [[String : Any]] , tiket : HTTPHeaders , completion : #escaping (_ done : Bool) -> Void ){
Alamofire.request(apiUrl, method : .post , parameters : parameter ,encoding : JSONEncoding.default, headers : tiket).responseJSON { (response) in
if response.result.isSuccess{
let responsejson : JSON = JSON(response.result.value!)
completion(true)
}
}
}
I am faily new to Alamofire itself, so forgive me if this is a simple one.
I would like to post a bank account object to intuit payments using Alamofire, however I keep getting the following error:
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
The documentation notes the following:
REQUEST URL
Sandbox Base URL: https://sandbox.api.intuit.com
Production Base URL: https://api.intuit.com
Operation: POST /quickbooks/v4/customers/<id>/bank-accounts
Content type: application/json
Header Parameters:
Request-Id required
Query Parameters:
id required
Request body
{
"name": "My Checking",
"routingNumber": "XXXXX0358",
"accountNumber": "XXXX4534",
"accountType": "PERSONAL_CHECKING",
"phone": "6047296480"
}
My attempts are as follows:
func saveBankAccountToIntuitPayments() {
let url = "https://api.intuit.com/quickbooks/v4/customers/" + userID! + "/bank-accounts"
let parameters: Parameters = [
"name": "John Doe",
"routingNumber": "123321456",
"accountNumber": "432123789012",
"accountType": "PERSONAL_CHECKING",
"phone": "55568925029"
]
ATTEMPT 1
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON(completionHandler: {
response in
print("running self.parseData(JSONData: response.data!)")
self.parseData(JSONData: response.data!)
})
ATTEMPT 2
let requestId = userID! + getTimeNow()
let header = [ "Request-Id" : requestId ]
Alamofire.request(url: url, method: .post, headers: header, parameters: parameters, encoding: JSONEncoding.default).responseJSON(completionHandler: {
response in
print("running self.parseData(JSONData: response.data!)")
self.parseData(JSONData: response.data!)
})
ATTEMPT 3
request(url, method: .post, parameters: parameters, headers: header).responseJSON(completionHandler: {
response in
print("running self.parseData(JSONData: response.data!)")
self.parseData(JSONData: response.data!)
})
}
This is the code for my json parser:
func parseData(JSONData: Data) {
do {
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard
print("printing readable JSON (below)")
print(readableJSON ?? "no JSON data was returned")
} catch {
print("errror occured (below)")
print(error)
}
}