How to add a value in Firebase to a Label in xcode? - swift

I have been Searching for 2 days on the internet now, and no sign of this. All i want to do is to take a value from RealTimeDataBase and put it in my label, apparently i can't find an answer and the people in youtube do it in a TableViewController. I tried some code but it doesn't work:
my code:
struct mylist {
let title : String!
}
var ref: DatabaseReference?
#IBOutlet var LabelTest: UILabel!
var posts = [mylist]()
#IBAction func nextTapped(_ sender: Any) {
//
//
let ref = Database.database().reference()
ref.child("ServiceA").queryOrderedByKey().observeSingleEvent(of: .value, with: { DataSnapshot in
let value = DataSnapshot.value as? NSDictionary
let title = value?["ServiceA"] as? String
self.posts.insert(mylist(title: title), at: 0)
})
post()
}
func post() {
let title = "Title"
let post = ["title": title]
let ref = Database.database().reference()
ref.child("ServiceA").childByAutoId().setValue(post)
LabelTest.text = mylist.title
}
please help me
i tried to follow this tutorial: https://www.youtube.com/watch?v=XIQsQ2injLo

FINALLY!!!
ok so here's how i did it:
let ref = Database.database().reference()
func getIncome() {
ref.child("ServiceA").child("Title").observeSingleEvent(of: .value, with: { DataSnapshot in
print(DataSnapshot)
let m = DataSnapshot.value as? String
self.LabelTest.text = m
})
}
ok special thanks to koen, his method works to :)

Related

Turning a firebase database value into a variable Swift

I have a var declared and I can retrieve the value from Firebase Database but when I then print the var in ViewDidLoad, it is empty, I don't understand what's wrong. Thanks everyone
This is the answer I get when I print the var : this is the language
//
var language: String = ""
//
func getUserLanguage(completion:((String) -> Void)?) {
let ref = Database.database().reference()
let uid = Auth.auth().currentUser!.uid
ref.child("users").child(uid).observe(.value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let languageResult = value?["language"] as? String ?? ""
completion?(languageResult)
}
)}
//
getUserLanguage { (languageResult) in
self.language = languageResult
}
// I print the value in ViewDidload
print("this is the language\(self.language)")
Try to print languageResult in function - maybe you don't get it inside the function and the variable is not assigned
Make language variable public
I think you are missing the asynchronous nature of your code here. The getUserLanguage function will call the completion only when it gets callback from observe(.value, with: { (snapshot) method of firebase. It is asynchronous. You won't get the value of language right after you call getUserLanguage in viewDidLoad.
override func viewDidLoad() {
super.viewDidLoad()
getUserLanguage { (language) in
print(language) // --> prints the expected value
self.language = language
}
print(language) // --> prints ""
}
func getUserLanguage(completion: #escaping (String) -> Void) {
let ref = Database.database().reference()
let uid = Auth.auth().currentUser!.uid
ref.child("users").child(uid).observe(.value, with: { (snapshot) in
let value = snapshot.value as? [String: Any]
let languageResult = value?["language"] as? String ?? ""
print("language: ", languageResult) // --> prints the expected value
completion(languageResult)
})
}

How to clear TableView and reload data again?

I have a function like this and when I reload with button this function collectionViewTable shows same data second time .How can I solve it ??
func getWallpaperFromDB(){
let databaseRef = Database.database().reference()
databaseRef.child("wallpapers").observe(DataEventType.childAdded) { (snapshot) in
if let value = snapshot.value! as? [String: Any] {
let categoryID = value["categoryID"] as! String
let categoryName = value["categoryName"] as! String
let wallpaperName = value["wallpaperName"] as! String
let wallpaperId = snapshot.key
let DBWallpaper = Wallpaper(categoryID: categoryID, categoryName: categoryName, wallpaperId: wallpaperId, wallpaperName: wallpaperName)
self.wallpapers.append(DBWallpaper)
self.collectionViewTable.reloadData()
}
}
}
#IBAction func slideMenuButton(_ sender: Any) {
getWallpaperFromDB()
}
You need to clear every call
#IBAction func slideMenuButton(_ sender: Any) {
wallpapers.removeAll()
getWallpaperFromDB()
}
You can empty your wallpapers array inside the closure function. That way every time the function is called the wallpapers array will be empty before the data is being fetched again. That way you won't have duplicate data.
func getWallpaperFromDB(){
let databaseRef = Database.database().reference()
databaseRef.child("wallpapers").observe(DataEventType.childAdded) { (snapshot) in
self.wallpapers = []
if let value = snapshot.value! as? [String: Any] {
let categoryID = value["categoryID"] as! String
let categoryName = value["categoryName"] as! String
let wallpaperName = value["wallpaperName"] as! String
let wallpaperId = snapshot.key
let DBWallpaper = Wallpaper(categoryID: categoryID, categoryName: categoryName, wallpaperId: wallpaperId, wallpaperName: wallpaperName)
self.wallpapers.append(DBWallpaper)
self.collectionViewTable.reloadData()
}
}
}
#IBAction func slideMenuButton(_ sender: Any) {
getWallpaperFromDB()
}

Code only retrieving one value from data in Firebase

As the title suggests, I'm trying to retrieve some data from firebase database, but my code's not working. I have three children (I guess that's how you call them) inside "Posts" called "title", "description" and "username" and I'm trying to get all of them and append them into a variable to use them later, but it only retrieves the first value of each of them, despite the fact that there are like 5 values. Anyone knows why?
By the way, I'm calling upon this function on my ViewDidLoad.
let postDB = Database.database().reference().child("Posts")
postDB.queryOrderedByKey().observeSingleEvent(of: .value) { (snapshot) in
if let snapshotValue = snapshot.value as? NSDictionary {
let postTitle = snapshotValue["title"] as? String
let postUsername = snapshotValue["username"] as? String
let postDesc = snapshotValue["description"] as? String
let postArray = postStruct(title: postTitle, description: postDesc, username: postUsername)
self.newPost.insert(postArray, at: 0)
}
import UIKit
import FirebaseDatabase
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: - variables
var postDB: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
// getting a node from database //
postDB = Database.database().reference().child("Posts")
// observing data changes //
postDB.observe(DataEventType.value) { (dataSnapshot) in
self.postArray.removeAll()
if dataSnapshot.childrenCount > 0 {
for post in dataSnapshot.children.allObjects as! [DataSnapshot] {
let object = post.value as! [String: Any]
let description = object["description"] as! String
let title = object["title"] as! String
let userName = object["username"] as! String
let model = postStruct(title: title, description: description, username: userName))
self.postArray.append(model)
}
}
self.tableView.reloadData()
}
}
}
Try this – the code replaces what you currently have in the snapshot handler.
if let firebaseList = snapshot.children.allObjects as? [FIRDataSnapshot] {
if let swiftList = snapshot.value as? [String:AnyObject] {
for firebaseItem in firebaseList {
let childID = firebaseItem.key as String
let swiftItem = swiftList[childID]
let postTitle = swiftItem?["title"] as? String
let postUsername = swiftItem?["username"] as? String
let postDesc = swiftItem?["description"] as? String
let postArray = postStruct(title: postTitle, description: postDesc, username: postUsername)
self.newPost.insert(postArray, at: 0)
}
}
}
}
Worked for me. It gets all the values now you just have to put them in an array
postDB.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull #NotNull Task<DataSnapshot> task) {
if(!task.isSuccessful()){
Log.e("firebase", "Error getting data; ", task.getException());
}else{
Log.d("firebase", String.valueOf(task.getResult().getValue()));
}
}
});

How can I retrieve data from firebase (Swift)

I am beginner and I would like to use swift as my programming language.
user can add register users and transfer money to each other, therefore when user type the photo number and email, the app can check if the typed number is registered in the firebase system
Any simple way to search if the user exist, thanks a lot
Here's the structure of the database
var ref: DatabaseReference!
var tref: DatabaseReference!
var handle : DatabaseHandle!
var usersArray = [NSDictionary?]()
var filteredUsers = [NSDictionary?]()
var user : NSDictionary?
override func viewDidLoad() {
super.viewDidLoad()
self.picker.isHidden = true
tref = Database.database().reference()
ref = Database.database().reference()
self.handle = self.ref?.child("users").child((Auth.auth().currentUser?.uid)!).child("contact").observe(.childAdded, with: { (snapshot) in
if let item = snapshot.value as? String {
self.pickerdata.append(item)
self.picker.reloadAllComponents()
}
})
self.picker.delegate = self
self.picker.dataSource = self
tref.child("users").queryOrdered(byChild: "phone").observe(.childAdded, with: {(snapshot) in
self.usersArray.append(snapshot.value as? NSDictionary)
})
print(usersArray.count)
}
#IBAction func ContactChange(_ sender: UITextField) {
filteredContent(searchText: contactText.text!)
print(filteredUsers.count)
print(usersArray.count)
print("ARRAY")
}
func filteredContent(searchText: String){
self.filteredUsers = self.usersArray.filter{ user in
let username = user!["phone"] as? String
return (username?.lowercased().contains(searchText.lowercased()))!
}
}
func findUsers(text: String){
self.handle = ref.child("users").queryOrdered(byChild: "phone").queryStarting(atValue: contactText.text!).queryEnding(atValue: contactText.text!+"\u{f8ff}").observe(.value, with: { snapshot in
if let item = snapshot.value as? String {
self.contact.append(item)
} else{
print("error")
}
})
}
The code above doesn't work much. Thanks so much for helping
The question is a little unclear but I think what the OP is asking is:
how to see if a user exists by their phone number?
If that's what's being asked, a node can be retrieved by query'ing for a child of that node. For example, let's create a query on the users node to find the child that contains the name: Kam querying by phone
let usersRef = firebaseRef.child("users")
let query = usersRef.queryOrdered(byChild: "phone").queryEqual(toValue: "2330504")
query.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
//need to iterate in case we find more than one match
for child in snapshot.children {
let snap = child as! DataSnapshot
let dict = snap.value as! [String: Any]
let name = dict["name"] as! String
print("found \(name)")
}
} else {
print("not found")
}
}
When this code is run it would print
found Kam
assuming the phone number is 2330504

Swift Firebase completion handler not working

My code calls Firebase and gets user information and user images. Once that's loaded, the app populates an image field and a text label. At least, that's what's supposed to happen. But instead, I'm getting fatal error: Index out of range error. What am I missing?
Here's my code:
#IBOutlet weak var userImage: UIImageView!
#IBOutlet weak var instructionsLabel: UILabel!
var currentUserName: String!
func loadExistingUsers(completion: #escaping () -> ()) {
ref.child("members").observe(.childAdded) { (snapshot: FIRDataSnapshot) in
if let dict = snapshot.value as? [String : Any] {
let userPhotoUrl = dict["profileImageUrl"] as! String
let userFirstName = dict["firstName"] as! String
let userBirthday = dict["birthday"] as! Int
let userPasscode = dict["passcode"] as! Int
let userGender = dict["gender"] as! String
let isUserChildOrParent = dict["childParent"] as! String
let storageRef = FIRStorage.storage().reference(forURL: userPhotoUrl)
storageRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in
let pic = UIImage(data: data!)
let user = User(profilePhoto: pic!,
userFirstName: userFirstName,
userBirthday: userBirthday,
userPasscode: userPasscode,
userGender: userGender,
isUserChildOrParent: isUserChildOrParent)
self.users.append(user)
self.users.sort(by: {$0.birthday < $1.birthday})
})
completion()
}
}
}
and my ViewDidLoad call:
loadExistingUsers {
self.currentUserName = self.users[0].firstName // error here
self.instructionsLabel.text = "Choose daily and weekly job assignments for \(self.users[0].firstName)."
self.userImage.image = self.users[0].photo
}
What am I doing wrong? I know my base code is good because I've tested it. Is it just the completion handler that's the problem? Any help would be greatly appreciated.