Create a dictionary in swift with alamofire - ios

Im trying to create a web request using alamofire in swift , by request object should be like this
{
"warranty": 0,
"descriptions": "string",
"product_name": "string",
"purchase_date": "23/10/2016",
"product_image": "string",
"product_receipt": "string",
"serial_number": "string",
"barcode_image": "string",
"serial_number_image": "string",
"product": {
"id": 1
},
"user": {
"id": 12
}
}
So in order to get this i have put my code as this
let parameters :[String:AnyObject] = [
"warranty":product.warrenty,
"descriptions":product.longDescription,
"product_name":product.initialName,
"purchase_date":product.purchaseDate,
"serial_number":product.serialCode,
"product": [
"id":product.id
],
"user": [
"id":userDefaults.getCustomerId()
]
]
But i when i do the request it seems that server doesn't accept this format , probably the way i assign
"product": {
"id": 1
},
"user": {
"id": 12
}
is not correct , what is the issue in here ? can some one point me the issue that i do here

I had the same issue and the problem was, i was missing the encoding option which you need to set .JSON. Match the below line with yours.
Alamofire.request(.POST, strURL, parameters: parameter as? [String : AnyObject], encoding: .JSON).responseJSON { (response: Response<AnyObject, NSError>) in

Related

how to define nested dictionary for alamofire POST request

Hi I have a nested dictionary that I need to pass to a function to make a POST request using alamofire.
this is the function that conduct the API call
func apiCall(productParameter: [String:String]) {
AF.request(dataURL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
debugPrint(response)
//some other code here.
}
}
in my viewController, I need to call this function:
apiCall(productParameter: [String:String])
the problem is I have a very complicated nested dictionary to pass... like this :
{
"userId": "string",
"price": {
"currency": "USD",
"amount": 99.96
},
"paymentModel": "string",
"description": "string",
"product": [
{
"description": "string",
"name": "string",
"images": [
"string"
]
}
]
}
do you know how to define the function and data type? thanks.
You should try [String : Any] in this case, so that your keys are always Strings but the values can be Strings, Dictionarys, Arrays and so on.

How can I post request json body in swift using Alamofire?

I need to make a POST request in the json body for my app backend but the response returns a failure. I assume my json formatting or encoding is wrong but I can't figure out what the problem is. I have attempted a lot of different solutions but I haven't been able to find one that works. Can anyone see which part of my code is responsible for the failure?
let headers: HTTPHeaders = [
"accept": "application/json",
"content-type": "application/json",
"authorization": self.authValue,
"x-iyzi-rnd": self.randomString,
"cache-control": "no-cache"
]
let parameters: [String: Any] = [
"price": "1.0",
"paidPrice": "1.1",
"paymentChannel": "mobile_ios",
"paymentCard": [
"cardHolderName": "card_name",
"cardNumber": "card_no",
"expireYear": "2030",
"expireMonth": "09",
"cvc": "123"
],
"buyer": [
"id": "123123123",
"name": "john",
"surname": "doe",
"identityNumber": "12345678902",
"email": "johndoe#gmail.com",
"registrationAddress": "nidakulegöztepemerdivenköymahborasokno1",
"city": "istanbul",
"country": "turkey",
"ip": "192.168.1.82"
],
"shippingAddress": [
"address": "nidakulegöztepemerdivenköymahborasokno1",
"contactName": "janedoe",
"city": "istanbul",
"country": "turkey"
],
"billingAddress": [
"address": "nidakulegöztepemerdivenköymahborasokno1",
"contactName": "janedoe",
"city": "istanbul",
"country": "turkey"
],
"basketItems": [
[
"id": "321",
"price": "0.3",
"name": "binocular",
"category1": "collectibles",
"itemType": "physical"
],
[
"id": "432",
"price": "0.5",
"name": "gamecode",
"category1": "game",
"itemType": "virtual"
],
[
"id": "543",
"price": "0.2",
"name": "usb",
"category1": "electronics",
"itemType": "physical"
]
],
"currency": "try"
]
Alamofire.request("https://api.iyzipay.com/payment/auth", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler: {
response in response
let jsonResponse = response.result.value as! NSDictionary
print(jsonResponse)
})
Is there any different way to post request json body?

Alamofire httpBody show 500 statusCode in swift 5

I am using Alamofire 5. I have put the parameters to httpbody. I have run it in Postman, and it is working fine. My body parameters are below.
{
"user_id": "user_id",
"username": "user_name",
"password": "pass",
"token": "",
"type_id": 100,
"country_id": 1,
"language_id": 1,
"customer_id": 1,
"parent_user_id": "",
"profile": {}
}
I have used below code to put the request using Alamofire 5. Here is the code:
func change_password() {
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"YumaSession": Global_Variable.globalValue.session_id
]
let parameters:Parameters = [
"user_id": "user_id",
"username": "username",
"password": txtPassword.text!,
"token": "",
"type_id": 100,
"country_id": 1,
"language_id": 1,
"customer_id": 1,
"parent_user_id": "",
"profile": []
]
AF.request( url,method: .put,parameters: parameters,encoding: URLEncoding.httpBody,headers: headers).responseJSON{ response in
switch response.result {
case .success(let responseData):
print("responseData-->",response.response!.statusCode)
case .failure(let error):
print("error--->",error)
}
}
}
Above code returns 500 status code. What is wrong above the code?
parameters.profile is defined with an array literal instead of an dictionary one. Fixed code below.
let parameters:Parameters = [
"user_id": "user_id",
"username": "username",
"password": txtPassword.text!,
"token": "",
"type_id": 100,
"country_id": 1,
"language_id": 1,
"customer_id": 1,
"parent_user_id": "",
"profile": [:]
]

How can I post an order into woocommerce using Alamofire?

I am trying to create an order from iOS to woo commerce using Alamofire. I am searching for a proper solution.
After trying to create an order I get this error:
{
code = "woocommerce_rest_cannot_create";
data = {
status = 401;
};
message = "Sorry, you are not allowed to create resources.";
}
Code:
let parameters: [String: AnyObject] = [
"consumer_key":"*******" as AnyObject, // here is my user name
"consumer_secret":"*******" as AnyObject, // here is my secret key
"shipping_total": "120.00" as AnyObject,
"total": "6015.00" as AnyObject,
"customer_id": 0 as AnyObject,
"billing": [
"first_name": "Faizul",
"last_name": "karim",
"company": "somecompany",
"address_1": "someAddress",
"address_2": "someAddress",
"city": "Dhaka",
"state": "Dhaka",
"postcode": "1203",
"country": "bd",
"email": "faizulkarim28#gmail.com",
"phone": "001929838939"
] as AnyObject,
"shipping": [
"first_name": "Faizul",
"last_name": "karim",
"company": "somecompany",
"address_1": "someAddress",
"address_2": "someAddress",
"city": "Dhaka",
"state": "Dhaka",
"postcode": "1203",
"country": "bd",
] as AnyObject,
"line_items":[
"id": 388,
"name": "Mens Casual Blazer - 40",
"product_id": 55677,
"variation_id": 57619,
"quantity": 1,
"tax_class": "",
"subtotal": "5895.00",
"subtotal_tax": "0.00",
"total": "5895.00",
"total_tax": "0.00",
] as AnyObject
]
Alamofire.request("https://infinitymegamall.com/wp-json/wc/v2/orders",method: .post, parameters: parameters)
.responseJSON{ response in
if let json = response.result.value {
print(json)
}
}
Are you sure your API Keys have write permissions? If GET works, it's possible that the key allows read only. Double check the permissions in your Woocommerce API Settings.

Why I cannot send multipartFormData with .POST parameters in Alamofire?

When I'm trying to send this:
Alamofire.upload(
.POST,
URL,
parameters: parameters,
multipartFormData: { multipartFormData in
it prints me the next error:
Type of expression is ambiguous without more context
I want to send my image file with the next parameters:
{
"user": {
"firstName": "ABC",
"email": null,
"birthDate": "1988-01-03",
"books": [{
"id": 1
}, {
"id": 2
}]
},
"locale": "en",
"sign": "It's me",
}
because of this structure, I cannot append it to multipart and I do not need send my parameters as a body of multipart, but as a parameters.
Is there any solutions for it?

Resources