swift check to see if firebase value is true or false - swift

Hello I'm retrieving some info from firebase the data I'm looking for are three child deep and consist to a boolean. When I Print the value im able to get the result but im not able to see if the result is true or false.
func userInfo() {
let dbRef = FIRDatabase.database().reference()
let stRef = FIRStorage.storage().reference()
dbRef.child("users/\(userBiD!)").observeEventType(.Value, withBlock: { snapshot in
let name = snapshot.value!["firstname"] as! String
let profileImage = snapshot.value!["profilePic"] as! String
let receivePostRequest = snapshot.value?["receivePostRequest"]
self.nameLabel.text = name
self.dbUserProfilePic(self.profilePhotoImageView, imageLink: profileImage)
let receivePost = snapshot.childSnapshotForPath("receivePostRequest")
let tags = receivePost.childSnapshotForPath("tags")
for child in tags.children {
/*
...
tags{
tag1 = true
tag2 = false
}
//I need to print all keys that have a true value
*/
}
})
}
firebase json

Since, according to the Firebase Docs,
.children is . . .
An iterator for snapshots of the child nodes in this snapshot. You can use the native for..in syntax.
. . . then you must use .value to access their data and .key to access their keys.
Therefore, you could do something like this.
func userInfo() {
let dbRef = FIRDatabase.database().reference()
let stRef = FIRStorage.storage().reference()
dbRef.child("users/\(userBiD!)").observeEventType(.Value, withBlock: { snapshot in
let name = snapshot.value!["firstname"] as! String
let profileImage = snapshot.value!["profilePic"] as! String
let receivePostRequest = snapshot.value?["receivePostRequest"]
self.nameLabel.text = name
self.dbUserProfilePic(self.profilePhotoImageView, imageLink: profileImage)
let receivePost = snapshot.childSnapshotForPath("receivePostRequest")
let tags = receivePost.childSnapshotForPath("tags")
for child in tags.children {
// NEW
if child.value == true {
print(child.key)
}
// NEW
}
})
}
Or, if you wanted to save all true values in an array.
func userInfo() {
let dbRef = FIRDatabase.database().reference()
let stRef = FIRStorage.storage().reference()
dbRef.child("users/\(userBiD!)").observeEventType(.Value, withBlock: { snapshot in
let name = snapshot.value!["firstname"] as! String
let profileImage = snapshot.value!["profilePic"] as! String
let receivePostRequest = snapshot.value?["receivePostRequest"]
self.nameLabel.text = name
self.dbUserProfilePic(self.profilePhotoImageView, imageLink: profileImage)
let receivePost = snapshot.childSnapshotForPath("receivePostRequest")
let tags = receivePost.childSnapshotForPath("tags")
for child in tags.children {
// NEW
var trueValues: [Bool] = []
if child.value == true {
trueValues.append(child.key)
}
// NEW
}
})
}

Related

Problem fetching data from firebase by using struct file

struct UserClass {
var babyName: String!
var babyHeight: String!
var babyWeight: String!
var babyURL: String!
var uid: String!
var reference:DatabaseReference!
var key: String!
init?(snapshot: DataSnapshot?) {
guard let value = snapshot?.value as? [String:AnyObject],
let uid = value["uid"] as? String,
let babyName = value["BabyName"] as? String,
let babyURL = value["BabyURL"] as? String,
let babyHeight = value["BabyHeight"] as? String,
let babyWeight = value["BabyWeight"] as? String else {
return nil
}
self.key = snapshot?.key
self.reference = snapshot?.ref
self.uid = uid
self.babyURL = babyURL
self.babyName = babyName
self.babyHeight = babyHeight
self.babyWeight = babyWeight
}
func getuserData() -> String {
return ("BabyName = \(babyName)")
}
}
func fetchCurrentUserInfo() {
var currentUserRef = Database.database().reference().child("Users").child("\(userID)")
handler = currentUserRef.queryOrderedByKey().observe(DataEventType.value, with: { (snapshot) in
print("User data = \(snapshot.value)")
let user = UserClass(snapshot: snapshot)
print(user?.babyName)
self.babyName.text = user?.babyName
})
}
I am getting user data but not user.babyName. How can I fix this?
May be this will help you, as the db structure is not mentioned in question. but you have to iterate children one by one and then use for loop to fetch the exact data from firebase.
reference = FIRDatabase.database().reference()
reference.child("Users").queryOrderedByKey().observe(DataEventType.value, with: { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots
{
let userId = child.childSnapshot(forPath: "userID").value! as! String
print(userId)
}
}
})

Retrieve firebase data from swift

I'm trying to retrieve data from a Firebase RealTime database, in order to put it on a list which will be used to display data on a TableView.
My problem is that even if I get some data, I haven't enough knowledge to access on arrays and other swift objects. Perhaps, I'm not using the good way to do what I want.
Here is an example of a row on Firebase :
Here is a function written in Swift in which I'm trying to build a list for each row object.
func displayStationsUsingSearch(){
let station = self.stationName
let CP = Int(self.searchedCP!)
// create searchRef or queryRef you name it
let stationsRef = Database.database().reference().child("Stations")
stationsRef.observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
/*if snapshot.value is NSNull {
print("not found")
} else {
// yes we got the user
let id = snapshot.value as! Int
}*/
for child in snapshot.children {
stationsRef.queryOrdered(byChild: "marque")
.queryEqual(toValue: "TOTAL ACCESS")
.observe(.value, with: { snap in
if let dict = snap.value as? [String: AnyObject] {
/*self.stationItem!.nomStation = dict["nomStation"] as! String
self.stationItem!.adresse = dict["adresse"] as! String
self.stationItem!.codePostal = dict["codePostal"] as! String
self.stationItem!.ville = dict["ville"] as! String
self.stationItem!.marque = dict["marque"] as! String
self.stationItem!.pays = dict["pays"] as! String
self.stationItem!.commentaire = dict["commentaire"] as! String
self.stationItem!.coordGPS = dict["coordGPS"] as! String*/
print(dict["nomStation"] as! String)
}
})
}
})
}
The lldb on Xcode workspace displays that :
Printing description of child:
Snap (-LdA6X8CfNY3bsPni31U) {
"DIESEL EXCELLIUM" = 0;
"DIESEL ULTIMATE" = 0;
GAZOLE = 0;
GPL = 0;
SP95 = 0;
"SP95 E10" = 0;
SP98 = 0;
SUPER = 0;
adresse = "RN1 Direction Moisselles";
codePostal = 95570;
commentaire = "";
coordGPS = "";
createdAt = "31/07/2018";
heureDebut = "";
heureFin = "";
id = 0;
marque = ESSO;
modifiedAt = "23/04/2019 18:53";
nomStation = "ESSO Moisselles";
pays = "";
saufJour = "";
services = "";
typeRoute = "";
ville = Moisselles;
}
(lldb)
Could you please help me to retrieve data on a list that I could append to display data on tableview ? Thank you.
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
}
}
You can use a swift Class Instead.
Swift Object:
import Foundation
class FirebaseTransactionData : NSObject{
var customer : FirebaseTransactionDataCustomer!
var driver : FirebaseTransactionDataCustomer!
var status : String!
init(fromDictionary dictionary: [String:Any]){
status = dictionary["status"] as? String
if let customerData = dictionary["customer"] as? [String:Any]{
customer = FirebaseTransactionDataCustomer(fromDictionary: customerData)
}
if let driverData = dictionary["driver"] as? [String:Any]{
driver = FirebaseTransactionDataCustomer(fromDictionary: driverData)
}
}
}
class FirebaseTransactionDataCustomer : NSObject{
var lat : Double!
var longField : Double!
init(fromDictionary dictionary: [String:Any]){
lat = dictionary["lat"] as? Double
longField = dictionary["lng"] as? Double
}
}
Firebase Method
ref.observe(DataEventType.value, with: { (snapshot) in
let value = snapshot.value as? [String:Any]
let datt = FirebaseTransactionData(fromDictionary: value!)
print("snapshot \(datt.status!)")
print("snapshot \(datt.customer.lat!)")
})

How to Update CollectionView Model with Firebase?

I am trying to intitialize my Collection View Model which holds a list of [Users] with a firebase snap that holds data.
Here is the Collection View Model code:
typealias JSON = [String:Any]
class HomeDataSource: Datasource {
var users: [User]
init?(with snapshot:DataSnapshot) {
var users = [User]()
guard let snapDict = snapshot.value as? [String: [String:Any]] else {return nil}
for snap in snapDict {
guard let user = User(dict: snap.value) else {continue}
users.append(user)
}
self.users = users
}
}
User Model:
struct User {
let name: String
let username: String
init?(dict: JSON) {
guard let name = dict["name"] as? String,
let email = dict["email"] as? String
else {return nil}
self.name = name
self.username = email
}
}
Firebase Snap:
Snap (users) {
8CVeHMNHI6hZAWj1zhGHEjPwYYz1 = {
email = "Silviu#isidors.sjsj";
name = Bshdjdj;
};
9CuqgR4Es7TOPPJQEpSnQXlfYnm1 = {
email = "Test#silviu.com";
name = "Test#silviu.com";
};
DBqGWlpdJKME570euqUz2rqI5Z83 = {
email = "Test#test.test";
name = Test;
};
}
Fetch Function:
func fetchUser() {
let ref = Database.database().reference().child("users")
ref.observe(.childAdded, with: { (snapshot) in
let user = User(dict: snapshot.value as! JSON)
self.users.append(user!)
print(self.users)
let new = HomeDataSource(with: snapshot)
print(new)
DispatchQueue.main.async(execute: {
self.datasource = new
self.collectionView?.reloadData()
})
}, withCancel: nil)
}
Right now, I am getting an array of Users from Firebase, however my collection view won't update.
My question is how should I update my Collection View Model and Fetching Function so it can fetch data from Firebase and Populate the Collection View Correctly?
So the problem was the node I was targeting. Removed "child("users")" form fetching function and targeted the whole users node with uids. Then I was looping the snapshot.value while I casted it in [String:[String:Any]], because each snapshot.valuelooked like this (key: "vijwUkzAlbgcqjAammfy0JuVMB33", value: ["name": Silviu, "email": Office#isidors.com]) Finally, I updated the HomeDataShource Class like this:
class HomeDataSource: Datasource {
var users: [User]
init(with snapshot:DataSnapshot) {
var users = [User]()
let snapDict = snapshot.value as? [String:[String:Any]]
for snap in snapDict! {
guard let user = User(snap: snap.value) else {continue}
users.append(user)
}
self.users = users
}

SWIFT4 Contextual type 'FPChat!.Type' cannot be used with dictionary literal

I need to initialize an object, and pass it through a prepareforsegue to another class.
Last line of the code below throws "Contextual type 'FPChat!.Type' cannot be used with dictionary literal"
if (segue.identifier == "chatmessages") {
let vc = segue.destination as! FPChatMessageViewController
//vc.currentChat = fPChat
}
}
fPchat = FPChat?
// Start the Chat
#IBAction func Chat(_ sender: UIButton) {
// Create a new entry in chats. This variable is passed with prepareforsegue
let chatRef = ref.child("chats").childByAutoId()
let chatId = chatRef.key
//fPchat = FPChat?
let fPchat = FPChat.currentChat(currentChatID: chatId)
Below chat class:
import Firebase
class FPChat {
var chatID = ""
var chatDate: Date!
var text = ""
var messages: [FPChatMessage]!
var author: FPUser!
var mine = true
// Calling FPChat.currentChat(id) I have back the FPChat object
static func currentChat(currentChatID: String) -> FPChat {
return FPChat(chatID: currentChatID)
}
private init(chatID: String) {
self.chatID = chatID
}
init(snapshot: DataSnapshot, andMessages messages: [FPChatMessage]) {
guard let value = snapshot.value as? [String: Any] else { return }
self.chatID = snapshot.key
if let text = value["text"] as? String {
self.text = text
}
guard let timestamp = value["timestamp"] as? Double else { return }
self.chatDate = Date(timeIntervalSince1970: (timestamp / 1_000.0))
guard let author = value["author"] as? [String: String] else { return }
self.author = FPUser(dictionary: author)
self.messages = messages
self.mine = self.author.userID == Auth.auth().currentUser?.uid
}
}
What I am doing wrong?

Firebase 2, accesing child values in snapshot produces nulls

I've been attempting to utilize firebase's snapshots, but when I try to access specific children, the output is a null.
var ref = FIRDatabaseReference.init()
func loadData {
ref = FIRDatabase.database().reference(
ref.child("Posts").child(postId).observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot.value?["PostText"] as! String) // Optional(<null>)
print(snapshot)
for child in snapshot.children {
if child.childSnapshotForPath("PostText").value == nil {
self.postText.text = ""
} else {
self.postText.text = child.childSnapshotForPath("PostText").value as? String // Optional(<null>)
print(child.childSnapshotForPath("PostText").value)
}
}
})
}
Output of print(snapshot)
Snap (84844) {
Author = lGAV1KUhSCP8hnFiKY1N9lBPrmmst1;
CommentsCount = 1;
Group = 665555;
ImageUrl = "http://i.telegraph.co.uk/multimedia/archive/03589/Wellcome_Image_Awa_3589699k.jpg";
PostText = "I like cakeh, but theijijijijijij truth is, it's too sweet. So SOMETIMES I dont eat it, but i LIKE CAKE.";
}
It looks like your snapshot is a Dictionary. Then you have to cast it as a Dictionary:
func loadData {
ref = FIRDatabase.database().reference(
ref.child("Posts").child(postId).observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot.value?["PostText"] as! String) // Optional(<null>)
print(snapshot)
let dict = snapshot.value as! Dictionary<String, AnyObject>
if let author = dict["Author"] as? String, commentsCount = dict["CommentsCount"] as? Int, group = dict["Group"] as? Int {
print("author \(author) commentsCount \(commentsCount), group: \(group)")
}
})
}
Do the same for ImageUrl and PostText, they should be cast as String