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

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!!

Related

How to get firebase data as a array

public func getAllItems(completion: #escaping (Result<[Item], Error>) -> Void)
{
database.child("Items").observe(.value, with: {snapshot in
guard (snapshot.value as? [[String: Any]]) == nil else{
completion(.failure(DatabaseError.failedToFetch))
return
}
var newUrlArray: [Item] = []
var newItemArray: [Item] = []
for child in snapshot.children{
if let childSnapshots = child as? DataSnapshot,
let dict = childSnapshots.value as? [String:Any],
let title = dict["title"] as? String,
let content = dict["content"] as? String,
let itemId = dict["itemid"] as? String,
let price = dict["price"] as? Int{
let item = Item(title: title, content: content, itemId: itemId, price: price, urs: newUrlArray)
newItemArray.append(item)
}
}
completion(.success(newDataArray))
})
}
My question is how can I get urls that shown in picture as an array or is it possible.
You need to go one level deeper into your JSON/Snapshot hierarchy to get the URLs.
If I remove the non-URL code for a moment for readability, it'd be something like:
for child in snapshot.children{
if let childSnapshots = child as? DataSnapshot,
let dict = childSnapshots.value as? [String:Any],
let urls = childSnapshots.childSnapshot(atPath: "urls").value as? [String:Any],
...
}
}
So urls above is another dictionary, where you can loop over its keys to get the URL values.

How to append data to array properly? Swift4

I've been trying to retrieve some data from firebase and store it in arrays. But I've got a problem when I try to append the data.
I can store the data into arrays only in the closure and outside of the closure, i all the sudden lose all the values inside of the arrays. Why does this happen? Please help me to find what I'm missing...
var names = [String]()
var txts = [String]()
var imgUrls = [String]()
Database.database().reference().child("Posts").child("dummy").observe(.value) { (snapshot) in
guard let snapshots = snapshot.children.allObjects as? [DataSnapshot] else {
return
}
for snap in snapshots {
let autoId = snap.key as String
Database.database().reference().child("Posts").child("dummy").child(autoId).observe(.value, with: { (snapshot) in
guard let data = snapshot.value as? [String: Any] else {return}
//name
guard let name = data["name"] as? String else {return}
self.names.append(name)
//image
guard let imgUrl = data["image"] as? String else {return}
self.imgUrls.append(imgUrl)
//txt
guard let txt = data["text"] as? String else {return}
self.txts.append(txt)
print(self.names) //this returns all data from firebase
print(self.imgUrls) //this returns all data from firebase
print(self.txts) //this returns all data from firebase
}
print(self.names) //this returns empty array
print(self.imgUrls) //this returns empty array
print(self.txts) //this returns empty array
}
Could it be because you are assigning the data inside a closure which could happen in a later time. So basically the last print statement occurs before the closure statements.
I will recommend you use didSet to understand the sequence. For example:
var names: [String] = [String]() {
didSet {
print(names) // this is print each time the value is set
}
}
var txts: [String] = [String]() {
didSet {
print(txts)
}
}
var imgUrls: [String] = [String]() {
didSet {
print(imgUrls)
}
}
Database.database().reference().child("Posts").child("dummy").observe(.value) { (snapshot) in
guard let snapshots = snapshot.children.allObjects as? [DataSnapshot] else { return }
for snap in snapshots {
let autoId = snap.key as String
Database.database().reference().child("Posts").child("dummy").child(autoId).observe(.value, with: { (snapshot) in
guard let data = snapshot.value as? [String: Any] else {return}
//name
guard let name = data["name"] as? String else {return}
self.names.append(name)
//image
guard let imgUrl = data["image"] as? String else {return}
self.imgUrls.append(imgUrl)
//txt
guard let txt = data["text"] as? String else {return}
self.txts.append(txt)
}
}

Read array from firebase once and put it into an array

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
}
}

firebase child values as string in array to populate a picker swift 3

How do you use Firebase values that have been placed into an array to poplulate a picker. This is the code I'm using to add values to an array and print them:
let dbRef1 = FIRDatabase.database().reference().child("Live Scoring Male")
dbRef1.observe(.childAdded, with: { snapshot in
let data = snapshot.value as? [String:Any] ?? [:]
let name = data["name"] as? String ?? ""
self.compArray.append(name)
print("\(name)")
})
However the array values aren't being loaded into the picker when I call:
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if (pickerView.tag == 1) {
return compArray[row]
}
}
This code works if I hard code the string in the array but not if I try to load the values from Firebase.
You need to reload the pickerView components to change it with new dataSource array.
let dbRef1 = FIRDatabase.database().reference().child("Live Scoring Male")
dbRef1.observe(.childAdded, with: { snapshot in
if let dic = snapshot.value as? [String:Any], let name = dic["name"] as? String {
self.compArray.append(name)
print("\(name)")
//Reload the pickerView components
self.pickerView.reloadAllComponents()
//Or you can reload the pickerView's specific component
self.pickerView.reloadComponent(0)
}
})
First you have to convert the snapshot to a dictionary and then access the name from the dictionary:
let data = snapshot.value as? [String:Any] ?? [:]
let name = data["name"] as? String ?? ""
self.compArray.append(name)

Working With Json in swift 3

I want to get long_name from this JSON file I can just access 'results' with this code:
let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?latlng=35.7229513,51.3566039&language=fa&key=AIzaSyBXOPT1jEYizWZHOKLwv4dhacgYTcmn3I4")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
}
else{
if let urlcontent = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlcontent, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:Any]
print(jsonResult["results"]!)
if let jsonResult = jsonResult["results"] as? [String: Any] {
if let address_components = jsonResult["address_components"] as? [String: Any] {
print(address_components)
if let long_name = address_components["long_name"] as? [String: Any] {
print(long_name)
}
}
}
}
catch{
print("json failed")
}
}
}
}
task.resume()
But I'm just getting result this is my JSON file:
https://maps.googleapis.com/maps/api/geocode/json?latlng=35.7339859%2C51.3393980&sensor=true_or_false&language=fa
Your result key contains Array as value not Dictionary so simply change [String:Any] to [[String:Any]] and then access address_components from the each dictionary objects of resultsArray, now address_components is also array of dictionary and long_name is inside that dictionary. So try like this.
if let resultsArray = jsonResult["results"] as? [[String: Any]] {
for dic in resultsArray {
if let addressArray = dic["address_components"] as? [[String:Any]] {
for address in addressArray {
if let longName = address["long_name"] as? String {
print(longName)
}
}
}
}
}

Resources