Read array from firebase once and put it into an array - arrays

How to read firebase array and put it into swift array? I'm trying to solve this problem for like 4 hours. What am I doing wrong?
ref.child("names").child("myNames").observe(.value) { (snapshot) in
if let item = snapshot.value as? String {
namesArray.append(item)
}
}

You should parse the snapshot as [String : Any]? and fetch the values in the dictionary.
ref.child("names").child("myNames").observe(.value) { (snapshot) in
if let itemDictionary = snapshot.value as? [String : Any] {
for (key, value) in itemDictionary {
// Another check for String
if let valueString = value as? String {
namesArray.append(valueString)
}
}
}
}

You are trying to unwrap an array of String as a single String, so that is why it's failing. Change to the following:
ref.child("names").child("myNames").observe(.value) { (snapshot) in
if let item = snapshot.value as? [String] {
namesArray = item
}
}

Related

Swift4, Firebase - Retrieve only value of key and put in array

I want to retrieve all the values of 'itemname' from Firebase and put them in my array generatedObjects. Now it seems like i get the parent, and also the key and value of its children, when i only want all values of 'itemname' ('Toiletry bag', 'Toothbrush' etc.). Not sure where to go from here, appreciate any help:
My code:
self.ref.child("lists").child("-LOXr5PoUvBn_tGNhql-").child(whatList!).observeSingleEvent(of: .value, with: { (snapshot) in
let children = snapshot.children
while let rest = children.nextObject() as? DataSnapshot{
print(rest.value)
//self.generatedObjects.append(rest.value as! [String: AnyObject])
}
},withCancel: nil)
Try this
func getData() {
ref.child("lists").child("-LOXr5PoUvBn_tGNhql-").child("mylist").observe(.childAdded) { (snapshot) in
let result = snapshot.value as? [String: Any]
let item = result!["itemname"]
//append item to your array
...
}
}
func fetchdata(toId: String)
{
Database.database().reference().child("Users").child(toId).observeSingleEvent(of: .value) { (snapshot) in
guard let dictionary = snapshot.value as? [String:Any] else {return}
let itemname = dictionary["itemname"] as! String
print(itemname)
}
}
does it helpfull!!

Creating an array out of Firebase Dictionary

I am trying to retrieve a dictionary from Firebase and extract each value from the dictionary and append it to an empty array, but my code doesn't work. I haven't even added the code for appending it to an array and when I run it, "error" is printed in the console.
This is what it looks like inside Firebase
And this is what my code looks like:
func convertAllMosaicsToArray() {
// retrieve and convert here
Database.database().reference().child("mosiacTitles").observe(.value, with: { (snapshot) in
if let dictionary = snapshot.value as? [Int : AnyObject] {
print(dictionary)
} else {
print("error")
}
})
}
static func load(_ completion: #escaping () -> ()) {
if let user = Auth.auth().currentUser {
let ref = Database.database().reference().child("users").child(user.uid).child("something")
ref.observe(.value, with: { (snapshot) in
if let data = snapshot.value as? [String : AnyObject] {
var arrayNeeded: [Int] = []
if let array = data["key"] as? [Int] {
arrayNeeded = array
}
}
completion()
})
}
}
The problem was using the if let statement to cast it as a [Int : AnyObject], it just needed to be changed to an [String]
Like this:
func retrieveMosaicTitles() {
// retrieve and convert here
Database.database().reference().child("mosaicTitles").observe(.value, with: { (snapshot) in
if let allMosaicTitles = snapshot.value as? [String] {
self.searchResultsVC.listOfMosaics = allMosaicTitles
} else {
print("error")
}
})
}

How to filter Dictionary of Array Swift3.0?

I've an Dictionary which contains Array and that Array has another Dictionary ant it also has another array. How do I get the last array by using 'Dictionary.Filter'.
For Example
Dict1->Array1->Dict2->Array2.
Here I need
Array2
I want to get "DeviceLsit" Array
Check this out! Based on your screenshot, I have managed to achieve it!
func filterArray() {
let dictPlist = Dictionary<String, Any>()
if let arrKeyName = dictPlist["key"] as? Array<Dictionary<String, Any>> {
let yourSecondArray = arrKeyName.filter({ (keyDict) -> Bool in
guard let _ = keyDict["keyName"] as? Array<Any> else {
return false
}
return true
})
}
}
Hope this helps!
if you want array of DeviceLists you can got through categories and get device lists
let root: [String: Any] = ["Categories": [ ["deviceList": ["1","2","3","4"]], ["deviceList": ["5","6","7","8"]] ]]
if let categories = root["Categories"] as? [Any] {
var deviceLists: [String] = []
for cat in categories {
if let cat = cat as? [String: Any], let deviceNames = cat["deviceList"] as? [String] {
deviceLists.append(contentsOf: deviceNames)
}
}
print(deviceLists)
}
here is the short anser :
Assume that your desired Array has Any Type. you can make it as you want like String , Int etc...!
let dict = [String:[[String:[Any]]]]()
let arr = dict.flatMap({($0.value).flatMap({($0.values)})}).last
print(arr) <-- your desired Array

Swift3 get element from array

I have a json string converted to string array like below:
let str = "{ \"dtResult\": [ { \"itmdtl_item_no\": \"AO406705959SE3\" }, { \"itmdtl_item_no\": \"AO406708959SE3\" } ] }"
let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
let result = json["dtResult"] as? [[String:Any]] ?? [ ]
let item = result[0] as! [String:Any]
print(item)
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
When i print out the result of item, i got the value like this:
["itmdtl_item_no": AO406705959SE3]
But i just want the string "AO406705959SE3", how can i do? Thanks.
First of all don't write
let result = json["dtResult"] as? [[String:Any]] ?? [ ]
If result is nil or empty the app will crash on result[0]
Instead write to check if the array exists and is not empty
if let result = json["dtResult"] as? [[String:Any]], !result.isEmpty {
let item = result[0] as! [String:Any]
// Now get the value for key "itmdtl_item_no"
if let itemNo = item["itmdtl_item_no"] as? String {
print(itemNo)
}
}

Swift: Parsing Arrays out of JSONs

[{"name":"Air Elemental","toughness":"4","printings":["LEA","BTD","7ED","8ED","9ED","10E","DD2","M10","DPA","ME4","DD3_JVC"]}]
I have a JSON where there is an array in each listing called "printings" as seen below, how would I take this array out of each listing and convert it into a string like "LEA-BTD-7ED". Here is what I have so far but its crashing.
let err : NSErrorPointer?
let dataPath = NSBundle.mainBundle().pathForResource("cardata", ofType: "json")
let data : NSData = try! NSData(contentsOfFile: dataPath! as String, options: NSDataReadingOptions.DataReadingMapped)
do{
var contents = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! [AnyObject]
for var i = 0;i<contents.count;++i{
let printing = contents[i]["printings"] as! String
}
}
Here's the code:
let path = dataPath!
if let JSONData = NSData(contentsOfFile: path)
{
do
{
if let dictionariesArray = try NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions()) as?
[[String: AnyObject]]
{
for dictionary in dictionariesArray
{
if let printingsArray = dictionary["printings"] as? [String]
{
let printingsString = printingsArray.joinWithSeparator("-")
print(printingsString)
}
}
}
}
catch
{
print("Could not parse file at \(path)")
}
}
Executing it prints "LEA-BTD-7ED-8ED-9ED-10E-DD2-M10-DPA-ME4-DD3_JVC"
You can't cast an Array (contents[i]["printings"]) to a String. What you want is Array's joinWithSeparator() method, like this:
let printing = contents[i]["printing"] as! Array
let printingStr = printing.joinWithSeparator("-")
(Actually, I'm not sure whether you need the as! Array; try it without it.)

Resources