Retrieving Data Using Firebase Swift

Swift retrieve data from Firebase

You are observing the childAdded event.

So your closure will only be executed when a new value I inserted into Users/Advertisements.

Try this code instead

Database
.database()
.reference()
.child("Users")
.child(Auth.auth().currentUser!.uid)
.child("Advertisements")
.queryOrderedByKey()
.observeSingleEvent(of: .value, with: { snapshot in

guard let dict = snapshot.value as? [String:Any] else {
print("Error")
return
}
let imageAd = dict["imageAd"] as? String
let priceAd = dict["priceAd"] as? String
})

The closure will be executed only once and "almost" immediately.

Retrieve Data from Firebase using where Query in Swift 4

You need to add a query:

ref.queryOrdered(byChild: "videoid").queryEqual(toValue: "12345").observeSingleEvent(of: .value, with: { snapshot in

more info here:

https://firebase.google.com/docs/reference/swift/firebasedatabase/api/reference/Classes/DatabaseQuery#queryorderedbychild

How to retrieve data from all the Users using Firebase and Swift

Looks like you misspelled the location key for your dictionary:

let location = userDict["Location"] as! [String: AnyObject]

Replace it with:

let location = userDict["location"] as! [String: AnyObject]

You can always put a breakpoint at the print line and see what your location dictionary looks like with po location in console.

Retrieve firebase data from swift

Try something like that:

Database.database().reference()
.child("Stations").
observeSingleEvent(of: .value, with: { (snapshot) in
guard let value = snapshot.value as? [String: Any] else {
return
}

var stations = [Station]()
for (key, value) in values {
guard let station = value as? [String: Any],
let adresse = station["adresse"] as? String,
let codePostat = station["codePostat"] as? String else {
continue
}
stations.append(Station(adresse: adresse, codePostat: codePostat))
}

// if you have some completion return retrieved array of stations
completion(stations)
})

struct Station {

private let adresse: String
private let codePostat: String

init(adresse: String, codePostat: String) {

self.adresse = adresse
self.codePostat = codePostat
}
}

Swift: how to retrieve data from firebase?

To read data from Firebase you attach a listener to a path which is what creates a FIRDatabase reference. A FIRDatabaseReference represents a particular location in your Firebase Database where there is a key-value pair list of children. So in your case, you have created a Firebase reference to the key "wins" which only points to a value and not a key-value pair. Your reference was valid up to this point:

    ref = Database.database().reference().child(passUserID) 

//did you mean FIRDatabase and not Database??

This FIRDatabaseReference points to the key passUserID which has a key-value pair list of children ["wins":"7"] and ["losses":"8"] (NOTE: a key is always a string). So from your FIRDatabase reference, you create your observer as follows and read the value of "wins":

   ref?.observe(.childAdded, with: { (snapshot) in

//Convert the info of the data into a string variable
if let getData = snapshot.value as? [String:Any] {

print(getData)

let wins = getData["wins"] as? String

print("\(wins)")

}

})

The Child added event will fire off once per existing piece of data, the snapshot value will be an individual record rather than the entire list like you would get with the value event. As more items come in, this event will fire off with each item. So if "losses" is the first record you might not get the value of "wins". Is this what you are trying to achieve? If what you really wanted to know is the value of "wins" at that particular location and to know if this value has ever changed you should use the .value observer as follows:

    ref?.observe(.value, with: { (snapshot) in

//Convert the info of the data into a string variable
if let getData = snapshot.value as? [String:Any] {

let wins = getData["wins"] as? String

print("\(wins)") //check the value of wins is correct

}

})

Or if you just wanted to get the know the value of wins just once and you are not worried about knowing if there any changes to it, use the "observeSingleEvent" instead of "observe".

EDIT

I saw your image and now realize you might also have a problem with your reference. Your ref should actually be something like:

    ref = FIRDatabase.database().reference().child("game-").child(passUserID)

You have obscured what "game" is but a valid reference to "wins" will include it.

SECOND EDIT

I will add the following so you can properly debug the problem. Use this pattern to observe the value and see if you get an error returned and what is says:

        ref.observe(.value, with: { (snapshot) in

print(snapshot)

}, withCancel: { (error) in

print(error.localizedDescription)

})

Normally it will give you an error if you cannot access that Firebase location because of a database rule. It will also be a good idea to see if print(snapshot) returns anything as above.

How to retrieve data from firebase using Swift?

Since I can not comment and I just want to ask something, I will remove this answer later on, but is your data in sync? Did you call the method yourreference.keepSynced(true)?

Firebase Retrieving Data in Swift

It gives you that warning message indexOn because you are doing a query.

you should define the keys you will be indexing on via the .indexOn
rule in your Security and Firebase Rules. While you are allowed to
create these queries ad-hoc on the client, you will see greatly
improved performance when using .indexOn

As you know the name you are looking for you can directly go to that node, without a query.

    let ref:FIRDatabaseReference! // your ref ie. root.child("users").child("stephenwarren001@yahoo.com")

// only need to fetch once so use single event

ref.observeSingleEventOfType(.Value, withBlock: { snapshot in

if !snapshot.exists() { return }

//print(snapshot)

if let userName = snapshot.value["full_name"] as? String {
print(userName)
}
if let email = snapshot.value["email"] as? String {
print(email)
}

// can also use
// snapshot.childSnapshotForPath("full_name").value as! String
})

Swift: Retrieve data from Firebase and display in table view

From what you have shown the culprit is the postId, you are using it to fetch data from Firebase and yet you haven't shown anywhere what its value is. When the user taps on an image, the postId is not transfered to the SiteViewController.

In the SiteViewController remove the ! and replace it with ?, put an initializer that will take the postID as a parameter.

var postId:String?

func initPost(forImage postId: String) {
self.postId=postId
}

In the previous news feed VC inside the segue or didSelectForRow(i don't know what you use for transition, initialize the SiteViewController, so when it is presented it knows which ID to retrieve data for.

Another thing that needs mentioning is that you are using observe but you are not removing the observers.

EDIT: this answer was based on me not knowing what your HomeVC looked like.

     if segue.identifier == "SiteSegue" {
let siteVC = segue.destination as! SiteViewController
let postId = sender as! String
siteVC.postId = postId

}

How to retrieve data from firebase properly with a url in Swift?

You didn't provide enough information, however, I think this might help you.

First, you need to add LiturgyFetcher to your DailyWorshipView:

@ObservedObject var liturgyFetcher = LiturgyFetcher()

Then you need a way to join DailyData with LiturgyData:

struct DailyData: Identifiable {
let id = UUID()
let name: String
let model: String
let text: String

// this is just the idea...
var title: String {
!model.isEmpty ? "\(name) (\(model))" : name
}
}

and filter liturgyFetcher.sermons variable to find your liturgy:

liturgyFetcher.sermons.first{ $0.title == dailydata.title }

Your DailyWorshipView may look like this (you may want to move filtering to the LiturgyFetcher):

struct DailyWorshipView: View {
@State private var model = DailyData.all()
@ObservedObject var liturgyFetcher = LiturgyFetcher()

var body: some View {
NavigationView {
List {
ForEach(model) { dailydata in
self.liturgyCell(dailydata: dailydata)
}
}
.navigationBarTitle(Text("Hours"))
}
}

func liturgyCell(dailydata: DailyData) -> some View {
NavigationLink(destination: LiturgyDetail(liturgy: liturgyFetcher.sermons.first{ $0.title == dailydata.title })) {
HStack {
Text(dailydata.name)
}
}
}
}

Then you can use LiturgyData in your LiturgyDetail view as desired:

struct LiturgyDetail: View {
let liturgy: LiturgyData?

var body: some View {
Text("\(liturgy?.title ?? "no liturgy found")")
}
}


Related Topics



Leave a reply



Submit