Alamofire send Array of Dictionaries in a parameter - ios

I have a POST API in which I send multiple parameters, one of those parameters has to be an array of dictionaries.
let arr = [
[
"id" : "1",
"price" : "10"
],
[
"id" : "2",
"price" : "20"
]
]
let params : Parameters = [
"param1" : "anyvalue1",
"param2" : "anyvalue2",
"param3" : arr,
]
When I use these parameters in Alamofire Request and hit the API, print(res.result.value) always returns unknown. Can anyone help me with this. Following is the way of requesting the API
Alamofire.request(url, method:.post, parameters: params).responseJSON{(res) in
print(res.result.value) //always shows 'unknown' as output
}

Try to make params a Dic of [String :Any ] like that :
let params : [String:Any] = [
"param1" : "anyvalue1",
"param2" : "anyvalue2",
"param3" : arr,
]

Related

Swift Error: Consecutive statements on a line must be separated by ';'

let email = MUser.sharedInstance.getUserEmail()
let json = [
"listIds": [""],
"contacts": [{ "email" : "\(email)" }]
];
I'm getting the error Consecutive statements on a line must be separated by ';' when running the code above. What am I doing wrong?
The problem is the dictionary email: email where {, } are not recognised keywords You can define your json like this :
let json = [
"""
"listIds": [""],
"contacts": [ {"email" : "\(email)" }]
"""
];
or if you prefer to construct your dictionary in contacts with code, you could do something like below:
let json = [
"listIds": [""],
"contacts": [[ "email" : "\(email)" ]]
];

How to create parameter for request body for calling api if parameters required nested info to pass

I have to create request body for calling api which have nested dictionary formate to pass parameter. I am unable to create parameter
parameter should be in below format
let parameters: [[String: Any]] = [
"contributionIds":[
"ms.vss-tfs-web.project-members-data-provider-verticals"
],
"dataProviderContext": [
"properties": [
"sourcePage": [
"url":"https://xxx.visualstudio.com/abc%20abc",
"routeId":"ms.vss-tfs-web.project-overview-route",
"routeValues": [
"project":"abc",
"controller":"Apps",
"action":"ContributedHub",
"serviceHost":"2e1bc96a-9bac-4e6e-9e33-eb460123a138 (xxxxx)"
]
]
]
]
]
Above data need to post to api for get response from API
Getting an error
Contextual type '[[String : Any]]' cannot be used with dictionary literal
remove type notation [[String: Any]] because you are specifying wrong notation based on your structure type notation is [String: Any]. if you will not define type notation then that is fine as well.
Try Below Solution,
let parameters: [String: Any] = [
"contributionIds":[
"ms.vss-tfs-web.project-members-data-provider-verticals"
],
"dataProviderContext": [
"properties": [
"sourcePage": [
"url":"https://xxx.visualstudio.com/VSO%20Client",
"routeId":"ms.vss-tfs-web.project-overview-route",
"routeValues": [
"project":"VSO Client",
"controller":"Apps",
"action":"ContributedHub",
"serviceHost":"2e1bc96a-9bac-4e6e-9e33-eb460123a138 (xxxx)"
]
]
]
]
]
OR
let parameters = [
"contributionIds":[
"ms.vss-tfs-web.project-members-data-provider-verticals"
],
"dataProviderContext": [
"properties": [
"sourcePage": [
"url":"https://xxx.visualstudio.com/VSO%20Client",
"routeId":"ms.vss-tfs-web.project-overview-route",
"routeValues": [
"project":"VSO Client",
"controller":"Apps",
"action":"ContributedHub",
"serviceHost":"2e1bc96a-9bac-4e6e-9e33-eb460123a138 (xxxx)"
]
]
]
]
] as [String : Any]

JSON to Array conversion

I'm trying to convert a JSON string to an array. The JSON string is:
[
{
"field_value" : "28 Aug 2017",
"field_data_type_combo_value" : "",
"field_data_type_category_id" : "1",
"form_id" : "19",
"field_id" : "133",
"message_unique_id" : "7941501245582800298",
"field_data_type_combo_id" : "0",
"field_data_type_id" : "1"
},
{
"field_value" : "",
"field_data_type_combo_value" : "",
"field_data_type_category_id" : "9",
"form_id" : "19",
"field_id" : "134",
"message_unique_id" : "7941501245582714588",
"field_data_type_combo_id" : "0",
"field_data_type_id" : "26"
},
{
"field_value" : "hk",
"field_data_type_combo_value" : "",
"field_data_type_category_id" : "6",
"form_id" : "19",
"field_id" : "135",
"message_unique_id" : "7941501245582699681",
"field_data_type_combo_id" : "0",
"field_data_type_id" : "17"
}
]
and my conversion code is
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String : AnyObject]
} catch {
print(error.localizedDescription)
}
}
The conversion result is always nil. I also checked that JSON string in Online JSON Viewer and the string is correct. Please help me guys.
You explicitely write in your call:
as? [String: AnyObject]
In other words, you ask Swift to take whatever JSON returned, check that it is a dictionary with String keys, and either return that dictionary or nil. Since your data is an array and not a dictionary, it returns nil. Exactly what you asked for, but not what you wanted.
What you are expecting is an array of dictionaries, not a dictionary. You should also use Any instead of AnyObject. So convert it using
as? [[String: Any]]
The outer [] means it is an array, the inner [String: Any] means the items in the array must be dictionaries with String keys and Any values.
And why are you using .mutableContainers? If you have a good reason that you can explain then use it. If you don't and just copied the code from somewhere then remove it.
That json isn't a dictionary on the top level but an array. You can see that from the [ ... ], it would be a dictionary if it was { ... }. Fix your code using the corresponding cast:
return try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [AnyObject]

Recursive Dictionaries in Swift 3

I have small structures like this:
let arguments = [ "a" : [ "b" : [ "c" : "d", "e" : "f", "g" : "h" ] ] ]
In Swift 2 I could pass them as NSDictionary parameter to other functions. Now its all error. Swift wants me to specify precisely the Dictionary types but since the structures vary its not possible. How to solve this?
Of course you can still pass a dictionary to a function in Swift 3.
If the dictionary structure is known
In this case, as suggested by sbarow just declare the dictionary type in the param of the function
let arguments = [ "a" : [ "b" : [ "c" : "d", "e" : "f", "g" : "h" ] ] ]
func foo(dict: [String: [String: [String: String]]]) {
print(dict)
}
foo(dict:arguments)
If the dictionary structure is unknown
In this case, if you only know your dictionary has a String as key then you can declare it like shown below
let arguments = [ "a" : [ "b" : [ "c" : "d", "e" : "f", "g" : "h" ] ] ]
func foo(dict: [String: Any]) {
print(dict)
}
foo(dict:arguments)

swift: Add multiple <key, value> objects to NSDictionary

I'm trying to add multiple objects to NSDictionary, like
var myDict: NSDictionary = [["fname": "abc", "lname": "def"], ["fname": "ghi", "lname": "jkl"], ...]
Is it even possible to do this? If not, please suggest a better way. I actually need to convert this NSDictionary to JSON string and send that to the server, so I need multiple objects in NSDictionary.
You can definitely make a dictionary of dictionaries. However, you need a different syntax for that:
var myDictOfDict:NSDictionary = [
"a" : ["fname": "abc", "lname": "def"]
, "b" : ["fname": "ghi", "lname": "jkl"]
, ... : ...
]
What you have looks like an array of dictionaries, though:
var myArrayOfDict: NSArray = [
["fname": "abc", "lname": "def"]
, ["fname": "ghi", "lname": "jkl"]
, ...
]
To get JSON that looks like this
{"Data": [{"User": myDict1}, {"User": myDict1},...]}
you need to add the above array to a dictionary, like this:
var myDict:NSDictionary = ["Data" : myArrayOfDict]
SWIFT 3.0
List item
Frist of all you can create NSArray and Then you can Set Array in NSMutableDictionary using setvalue(forKey:) default method.
var arrFname : NSArray!
arrFname = ["abc","xyz","mno"]
var arrLname : NSArray!
arrFname = ["tuv","xuv","swift"]
var dicSet : NSMutableDictionary!
dicSet.setObject(arrFname, forKey : "Fname")
dicSet.setObject(arrLname, forKey : "Lname")
print(dicSet)
var tempDict = NSMutableDictionary()
tempDict.setValue("sam", forKey : "one")
print(tempDict["one"] ?? "1")

Resources