How to post array of single value in alamofire? - ios

I have to post json object.
One important thing, I have to post array of single value.
look at below code.
var pagingOption: [String: Any] = ["page": page,
"rowsPerPage": 20,
"sort": ["id": sortOption.rawValue,
"direction": "DESC"],
"searchStatues": ["accept"]]
searchStatuses is must array. But If I send this code, searchStatuses is not posted array.
If I add more value like this
var pagingOption: [String: Any] = ["page": page,
"rowsPerPage": 20,
"sort": ["id": sortOption.rawValue,
"direction": "DESC"],
"searchStatues": ["accept", "asdf", "asdf"]]
Then delivered array.
If I have only single value, How can I do that??

You can do it this way.
let searchValues: [String] = []
searchValues = ["accept", "asdf", "asdf"]
var pagingOption: [String: Any] = ["page": page,
"rowsPerPage": 20,
"sort": ["id": sortOption.rawValue,
"direction": "DESC"],
"searchStatues": searchValues]

Related

Firebase Analytics begin_checkout Items

Recently, I've implemented Firebase Analytics AnalyticsEventBeginCheckout event.
But it seems AnalyticsParameterItems not be sent to Firebase.
My code :
var jeggings: [String: Any] = [
AnalyticsParameterItemID: "SKU_123",
AnalyticsParameterItemName: "jeggings",
AnalyticsParameterItemCategory: "pants",
AnalyticsParameterItemVariant: "black",
AnalyticsParameterItemBrand: "Google",
AnalyticsParameterPrice: 9.99,
]
// A pair of boots
var boots: [String: Any] = [
AnalyticsParameterItemID: "SKU_456",
AnalyticsParameterItemName: "boots",
AnalyticsParameterItemCategory: "shoes",
AnalyticsParameterItemVariant: "brown",
AnalyticsParameterItemBrand: "Google",
AnalyticsParameterPrice: 24.99,
]
var checkoutParams: [String: Any] = [
AnalyticsParameterCurrency: "USD",
AnalyticsParameterValue: 14.98,
AnalyticsParameterCoupon: "SUMMER_FUN"
];
checkoutParams[AnalyticsParameterItems] = [jeggings, boots]
// Log checkout event
Analytics.logEvent(AnalyticsEventBeginCheckout, parameters: checkoutParams)
This code is the tutorial code from Firebase.
It seems AnalyticsParameterItems not been send, but if I send item_id and item_name, these 2 fields appear on my event datas
Any solution ?

How to consume an API response with Swift

I am trying to make an API request to get an API response I am getting all the elements but I am facing braces issue I want a whole response and "order_devices" key, in {} braces but I am getting these in [] braces.
the array in which i am passing value,
var popUpArray :[[String:AnyObject]] = []
then on btn click i am saving values in dictionary
#IBAction func btnSave(_ sender: Any) {
let popupDict = (["quantity": Int(txtEnterQuantity.text!), "name": lblDeviceName.text,"id": deviceDict["id"], "region":1, "system_integrated":1 ])as! [String:AnyObject]
and then passing the same dictionary value as parameter
let passDict = [
"dealer_id":dropDownId!,
"client_id":dropDownId!,
"distributor_id":searchBarId!,
"emp_id":UserId,
"comments":CommentKey!,
"accepted_by":0,
"valid_from":strDate!,
"valid_upto": 0,
"order_devices":popupDict
] as [String : Any]
if Reachability.isConnectedToNetwork() {
showActivityIndicator()
Alamofire.request("http://13.232.230.41/IAC_CRM/public/api/createOrder", method: .post, parameters: passDict, encoding: JSONEncoding.default, headers: [:])
.responseJSON { (response) in
i am getting this response ,
[
"comments": "demo",
"dealer_id": 3,
"valid_from": "6-3-2019",
"distributor_id": 72,
"client_id": 3,
"accepted_by": 0,
"emp_id": 33,
"valid_upto": 0
"order_devices":
[
[
"id": 1,
"quantity": 10,
"region": 1,
"system_integrated": 1
]
,
[
"id": 2,
"quantity": 12,
"region": 1,
"system_integrated": 1
]
]
]
i want this response,
{ "dealer_id":"1", "client_id":"2", "distributor_id":"2",
"emp_id":"1", "comments":"IAC test device comments", "accepted_by":0,
"valid_from":"2019-01-24", "valid_upto":"1", "order_devices":[
{
"device_id":"1",
"quantity":"1", "region":1, "system_integrated":1
}
,
{
"device_id":"2",
"quantity":"1"
"region":1,
"system_integrated":1
}
] }
means i want whole response and "order_devices" key in "curly braces"{} .
There is nothing wrong with request or response, your are getting response what your API is returning, You should ask you backend developer Or Api Provider to Give you response in form of your requirement i mean proper formatted Right now its in form of Array.

Adding to dictionary dynamically

I 'm having an array of dictionary like so...
[
{
"id" : "3",
"sellingPrice" : "520",
"quantity" : "15"
},
{
"id" : "5",
"sellingPrice" : "499",
"quantity" : "-1"
},
{
"id" : "8",
"sellingPrice" : "500",
"quantity" : "79"
}
]
Now I want to add to the dictionary another key called remaining_balance with a value of 420,499 & 500 respectively. How can I achieve this..? Hope somebody can help...
It seems like you want to add a value to your dictionary that is an array:
var arrDict = Array<Dictionary<String,Any>>() //Your array
arrDict.append(["id":"3","sellingPrice":"520","quantity":"13"])
arrDict.append(["id":"5","sellingPrice":"43","quantity":"32"])
arrDict.append(["id":"8","sellingPrice":"43","quantity":"33"])
let arrValue = ["420","499","500"] //Your remaining value in array
print("Before ",arrDict)
for (index,dict) in arrDict.enumerated() {
var dictCopy = dict //assign to var variable
dictCopy["remaining_balance"] = arrValue[index]
arrDict[index] = dictCopy //Replace at index with new dictionary
}
print("After ",arrDict)
EDIT
If you are able keep an index of an array it would be possible,
Assuming that you have the index of an array
var dictCopy = arrDict[index]
dictCopy["remaining_balance"] = "666" //Your calculated value
arrDict[index] = dictCopy //Replace at index with new dictionary
var newKV = [["remaining_balance": "420"],["remaining_balance": "490"],["remaining_balance": "500"]]
let array = [["id":"3", "sellingPrice":"520", "quantity":"15"], ["id":"5", "sellingPrice":"520", "quantity":"15"], ["id":"8", "sellingPrice":"520", "quantity":"15"]]
let newArray = array.enumerated().map { (index : Int, value: [String: String]) -> [String: String] in
var dic = value
dic.merge(newKV[index]) { (_, new) -> String in
new
}
return dic
}
You could achieve it by mapping your array:
var myArray = [["id": "3", "sellingPrice": "520", "quantity" : "15"], ["id": "5", "sellingPrice": "499", "quantity" : "-1"], ["id": "8", "sellingPrice": "500", "quantity" : "79"]]
print(myArray)
/*
[["id": "3", "sellingPrice": "520", "quantity": "15"],
["id": "5", "sellingPrice": "499", "quantity": "-1"],
["id": "8", "sellingPrice": "500", "quantity": "79"]]
*/
print("___________________")
var remainingBalanceDesriedValue = 420
myArray = myArray.map { (dict: [String: String]) -> [String: String] in
var copyDict = dict
copyDict["remaining_balance"] = "\(remainingBalanceDesriedValue)"
remainingBalanceDesriedValue = (remainingBalanceDesriedValue == 420) ? 499 : (remainingBalanceDesriedValue == 499) ? 500 : 420
return copyDict
}
print(myArray)
/*
[["sellingPrice": "520", "quantity": "15", "id": "3", "remaining_balance": "420"],
["sellingPrice": "499", "quantity": "-1", "id": "5", "remaining_balance": "499"],
["sellingPrice": "500", "quantity": "79", "id": "8", "remaining_balance": "500"]]
*/
Let's assume you have an array of dictionaries like so:
var arrayOfDictionaries = [
[
"id": 3,
"sellingPrice": 520,
"quantity": 15
]
]
It is important that arrayOfDictionaries is not a let constant, otherwise it is considered immutable and you can not call append on it.
Now you init a new dictionary like:
let newDictionary = [
"id": 10,
"remaining_balance": 420,
"quantity": 15
]
Now add the newDictionary like
arrayOfDictionaries.append(newDictionary)
If the order is important
If the order is important there are a couple of ways to go about that.
When calling append the new value (in this case the new dictionary) will always be inserted at the bottom of the array.
If for some reason you can not call append in the correct order you could use insert, which inserts your dictionary at a specific position.
Yet another way is to append the values wildly and after you are done, call sort on the array.
Improvement Tips
Notice that for the values I did not use strings, as you only have numbers like "id" : 30.
Also, if you want the second key to be called remaining_balance you should call the first key selling_price instead of sellingPrice. Because of conistency.
Alternative approach
As far as I have understood you are trying to implement some software that is responsibly for selling some products.
I think you are tackling this problem from a completely wrong side.
I think you should read about database relationships. Selling products actually is a very common problem.
Maybe this will help you. I would offer a possible solution myself, but I think this misses the point of your question.
If you decide to use the database approach, you won't necessarily have to use a database. You can take the approach and implement it using simple structs/classes/arrays.
I noticed this question lacks an extension answer, yes.. I'm gonna be that guy, so here it is. This could be made more generic by supporting other types of dictionaries, feel free to pitch in ;)
Inspiration from #eason's answer.
var newKV = [["remaining_balance": "420"],["remaining_balance": "490"],["remaining_balance": "500"]]
var array = [["id":"3", "sellingPrice":"520", "quantity":"15"], ["id":"5", "sellingPrice":"520", "quantity":"15"], ["id":"8", "sellingPrice":"520", "quantity":"15"]]
extension Array where Element == [String: String] {
enum UniquingKeysStrategy {
case old
case new
}
mutating func merge(with target: Array<Element>, uniquingKeysWith: UniquingKeysStrategy = .new) {
self = self.merged(with: target)
}
func merged(with target: Array<Element>, uniquingKeysWith strategy: UniquingKeysStrategy = .new) -> Array<Element> {
let base = self.count > target.count ? self : target
let data = self.count > target.count ? target : self
return data.enumerated().reduce(into: base, {
result, data in
result[data.offset]
.merge(data.element, uniquingKeysWith: {
old, new in
if strategy == .new { return new }
return old
})
})
}
}
let mergedArrays = newKV.merged(with: array, uniquingKeysWith: .old)
array.merge(with: newKV)
Happy Coding :)

Post JSON request in Swift 3

I need to post JSON data that looks like this :
{ “orders”:[ {“id”: 208, “quantity”: 1 },{“id”: 212, “quantity”: 2},{“id”: 202, “quantity”: 5}, ...etc ],“HHStatus”: “1 }
I have the following variable :
var orders : [ShoppingCart] = []
that contains data as :
[Crash.ShoppingCart(drinkId: 743, drinkName: "aqua", drinkPrice: "2.26", drinkQuantity: 2), Crash.ShoppingCart(drinkId: 715, drinkName: "yellow", drinkPrice: "6.92", drinkQuantity: 1), Crash.ShoppingCart(drinkId: 738, drinkName: "blue", drinkPrice: "4.69", drinkQuantity: 2)]
...etc
I am able to post the request using :
for order in orders {
let orderId = order.drinkId
let orderQuantity = order.drinkQuantity
let parameters = ["orders": [["id": orderId, "quantity": orderQuantity]], "HHStatus": orderHHStatus!] as [String : Any]
let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
but then I want the whole order not just one id and one quantity,
and I have tried using :
let orderId = orders.map { $0.drinkId }
let orderQuantity = orders.map { $0.drinkQuantity }
let parameters = ["orders": [["id": orderId, "quantity": orderQuantity]], "HHStatus": orderHHStatus!] as [String : Any]
let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
but then I end up with something like this :
["HHStatus": "0", "orders": [["id": [743, 715, 738], "quantity": [2, 1, 2]]]]
How can I send all the ids and quantities in one request?
I can't figure out how to get something like :
["orders": [["id": orderId, "quantity": orderQuantity],["id": orderId, "quantity": orderQuantity], ["id": orderId, "quantity": orderQuantity]], "HHStatus": orderHHStatus!]
so many thanks for any help provided!
Map the ShoppingCart array to an array of dictionaries with the map function:
let mappedOrders = orders.map { ["id" : $0.drinkId, "quantity" : $0.drinkQuantity] }
Create the parameters dictionary
let parameters : [String:Any] = ["orders" : mappedOrders, "HHStatus" : orderHHStatus!]
Don't pass the .prettyPrinted option, the server doesn't care about aesthetics.
Omit the options parameter.

Create a particular JSON Structure in Swift

I'm having trouble creating a specific structure in JSON with Swift. I use Swifty JSON for parsing but I can't figure out how to create one.
I have this array which is filled by Id's and quantity Ints of products in a shopping basket . I need to get the array into my JSON but I don't know how.
If you could help me with this I would be very glad :)
var productArray = Array<(id: Int,quantity: Int)>()
let jsonObject: [String: AnyObject] = [
"order": 1,
"client" : 1,
"plats": [
for product in productArray
{
"id": product.id
"quantity": product.quantity
}
]
]
You can't just start looping through stuff while defining your dictionary. Here's another approach.
First, create your array:
var productArray = Array<(id: Int,quantity: Int)>()
Add some products (for testing):
productArray += [(123, 1000)]
productArray += [(456, 50)]
Map this array into a new array of dictionaries:
let productDictArray = productArray.map { (product) -> [String : Int] in
[
"id": product.id,
"quantity": product.quantity
]
}
Use the new mapped array in your JSON object:
let jsonObject: [String: AnyObject] = [
"order": 1,
"client" : 1,
"plats": productDictArray
]
You are not supposed to do any kind of looping/condition making block of codes while creating Array's or Dictionary. For that you need to execute that piece of code outside, create a variable and use it.
Do try this way.
var productArray = Array<(id: Int,quantity: Int)>()
var prods = [[String:Int]]()
for product in productArray
{
var eachDict = [String:Int]()
eachDict["id"] = product.id
eachDict["quantity"] = product.quantity
prods.append(eachDict)
}
let jsonObject: [String: AnyObject] = [
"order": 1,
"client" : 1,
"plats": prods
]

Resources