Firebase Real Database data fetching - ios

I am trying the get the following values as variables
But my code gives me nil
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let userInfo = value?["UserInfo"] as? NSDictionary
let data = userInfo?["lat"] as? String ?? ""
print(data)
// ...
}) { (error) in
print(error.localizedDescription)
}
ًWhat am I missing ?

You have just to do a small change here:
let data = userInfo?["lat"] as? String ?? ""
Latitude is not a String, but an Int, so cast as Int:
let data = userInfo?["lat"] as? Int ?? 0

Related

How to convert items in optional Dictionary to individual strings

I am trying to convert items in an optional dictionary into individual strings so I can loop through them and convert them into URLs. But have been unable to do so.
Here is function which I use to fetch images from firebase which returns this optional dictionary which is also included below:
func fetchAllUsersImages() {
print("inside func")
self.ref.child("Posts").child(self.userID).child(self.postNum).observe(.childAdded, with: { snapshot in
print("inside closure")
// print(URL(string: snapshot.value as! String))
// let postSnap = snapshot.childSnapshot(forPath: self.postNum)
// let imageUrlSnap = postSnap.childSnapshot(forPath: "ImageUrl")
print(snapshot.value, "value")
// guard let allImages = imageUrlSnap.children.allObjects as? [DataSnapshot] else { return print("the code failed here")}
guard let allImages = snapshot.value as? [DataSnapshot] else { return print("the code failed here")}
// let snapshotVal = snapshot.value
// let snapshotValValue = snapshotVal as! String
// print(snapshotValValue, "snapshot as string value")
for image in allImages {
print(image, "image")
}
print(snapshot.key, "key")
print(snapshot.value, "value")
print(snapshot.children, "cjildren")
print(allImages)
print()
})
}
Output of snapshot.value:
Optional({
image1 = "https://firebasestorage.googleapis.com/v0/b/base.appspot.com/o/ijzAnEdyKNbhPsQVH6a8mOa1QpN2%2Fpost1%2Fimage1?alt=media&token=c2f396fd-717d-4192-909a-db390dd23143";
image2 = "https://firebasestorage.googleapis.com/v0/b/atabase.appspot.com/o/ijzAnEdyKNbhPsQVH6a8mOa1QpN2%2Fpost1%2Fimage2?alt=media&token=359b8527-f598-4f9a-934e-079cee21fd15";
})
Based on the answer provided I did the followoing:
func fetchAllUsersImages() {
print("inside func")
self.ref.child("Posts").child(self.userID).child(self.postNum).observe(.childAdded, with: { snapshot in //error here
var images: [URL] = []
if let snapShotValue = snapshot.value as? [String: String] {
for (_, value) in snapShotValue {
if let imageURL = URL(string: value) {
print(imageURL, "image url here")
let imageAsData = try Data(contentsOf: imageURL)
let image = UIImage(data: imageAsData)
let ImageObject = Image()
ImageObject.image = image
self.arrayOfImgObj.append(ImageObject)
self.tableView.reloadData()
}
}
}
})
}
However on the 3rd line I get
Unable to infer closure type in the current context
Edit:
To fix this error put the code, at the deepest part of the code, in a do block amd include a catch block also. This will fix the error.
Well first you need to check if the optional Dictionary exists then loop the dictionary for each key-value pair. Here is a way to do it:
var imageURLs: [URL] = []
if let snapShotValue = snapshot.value as? [String: String] { // Cast optional dictionary to a Dictionary of String keys and String values
// Cast would fail if snapshot.value is nil or has a different Dictionary setup.
for (key, value) in snapShotValue { // you can change key to _ since we are not using it
if let imageURL = URL(string: value) { // Get URL value from string
imageURLs.append(imageURL) // Add new URL to parsed URLs
}
}
}
So once the process is finished you'll have the images in imageURLs variable.

Swift firebase get data

How can I get name, quant from this structure:
Im try this:
var handle: DatabaseHandle?
var ref: DatabaseReference?
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
handle = ref?.child("Цитаты").child("Из Книг").child("Дорогой звезд").child("Quote1").observe(.childAdded, with: { (snapshot) in
let user = snapshot.value
print(user!) //text from name + 10 + Quote1
}
When I print snapshot.value it's give me data from Quote1 , but I want to show name in textField and quant in label I try this:
ref = Database.database().reference()
handle = ref?.child("Цитаты").child("Из Книг").child("Дорогой звезд").child("Quote1").observe(.childAdded, with: { (snapshot) in
let user = snapshot.value
if let us = user!["name"] as? String {
if let quant = user!["quant"] as? String{
self.quoteTextField.text = us
self.quotelabel.text = quant
}
}
And have error. How can I add data from snapshot.value to label and textField?
As I was checking your screen, quant is an Int not String, so try this
ref = Database.database().reference()
handle = ref?.child("Цитаты").child("Из Книг").child("Дорогой звезд").child("Quote1").observe(.childAdded, with: { (snapshot) in
//let username = snapshot.value as? NSDictionary
let user = snapshot.value as? [String: Any]
if let us = user!["name"] as? String {
if let quant = user!["quant"] as? Int {
self.quoteTextField.text = us
self.quotelabel.text = quant.description
}
}
}
You need to cast the snapshot.value as a dictionary -
let user = snapshot.value as? NSDictionary
You should also consider safely unwrapping your optionals -
let name = user?["name"] as? String ?? ""
let quant = user?["quant"] as? Int ?? 0

manually entered data in firebase issue

I am manually entering in data into my database and the only variable not getting passed from my database is the author and I do not know where I am going wrong.
func getAllArticles(handler: #escaping (_ articles: [Article])-> ()){
var articleArray = [Article]()
REF_ARTICLES.observeSingleEvent(of: .value) { (articleMessageSnapshot) in
guard let articleMessageSnapshot = articleMessageSnapshot.children.allObjects as? [DataSnapshot] else {return}
for article in articleMessageSnapshot {
let content = article.childSnapshot(forPath: "content").value as? String ?? "no content"
let author = article.childSnapshot(forPath: "author").value as? String ?? "no author"
let twitterHandle = article.childSnapshot(forPath: "twitterHandle").value as? String ?? "none"
let articleTitle = article.childSnapshot(forPath: "articleTitle").value as? String ?? "no title"
let date = article.childSnapshot(forPath: "date").value as? String ?? "no date"
let article = Article(content: content, author: author, twitterHandle: twitterHandle, ArticleTitle: articleTitle, date: date)
articleArray.append(article)
}
handler(articleArray)
}
}
Please check out below code
var articleArray = [Article]()
//REF_ARTICLES
let ref = Database.database().reference().child(“articles”)
ref.observe(.childAdded, with: { (snapshot) in
print(snapshot)
guard let dictionary = snapshot.value as? [String : AnyObject] else {
return
}
let articleObj = Article()
articleObj.Content = dictionary["content"] as? String
articleObj.Author = dictionary["author"] as? String
articleObj.Twitterhandle = dictionary["twitterHandle"] as? String
articleObj.Title = dictionary["articleTitle"] as? String
articleObj.Date = dictionary["date"] as? String
self. articleArray.append(articleObj)
}, withCancel: nil)
}
I am also working on similar app where i am storing data to firebase and retrieving. Below approach i used to fetch the data from firebase database. Please try once.
func getAllArticles(handler: #escaping (_ articles: [Article])-> ()) {
Database.database().reference().child("Articles").observe(.childAdded, with: { (snapshot) in
print("articles = \(snapshot)")
if let dict = snapshot.value as? [String: Any] {
let article = Article()
article.articleTitle = dict["articleTitle"] as? String
article.author = dict["author"] as? String
article.twitterHandle = dict["twitterHandle"] as? String
article.date = dict["date"] as? String
article.content = dict["content"] as? String
self.articleArray.append(article)
}
handler(articleArray)
}, withCancel: nil)
}
im not sure what the underlying issue was, but i fixed it by deleting "author" from the firebase tree and then adding it back

swift 3 firebase snapshot if value equal to ... fetch

I'm Trying to check if the rooms's value 'Owner' equals to the current user id if so then fetch all data including the key value and continue checking other children of 'rooms'
I was trying, but I fail finding the solution though it might seem easy so please help me with your suggestions or ideas. My code so far :
Database.database().reference().child("rooms").queryOrdered(byChild: "Owner").observeSingleEvent(of: .value, with: { (snapshot) in
let currentUser = Auth.auth().currentUser?.uid
if !snapshot.exists() {
print("No data found")
return
}
var rooms = snapshot.value as! [String:AnyObject]
let roomKeys = Array(rooms.keys)
for roomKey in roomKeys {
guard
let value = rooms[roomKey] as? [String:AnyObject]
else
{
continue
}
let title = value["title"] as? String
let description = value["description"] as? String
let roomPictureUrl = value["Room Picture"] as? String
let longitude = value["Longtitude"] as? String
let latitude = value["Latitude"] as? String
let dateFrom = value["Date From"] as? String
let dateTo = value["Date To"] as? String
let owner = value["Owner"] as? String
let myRooms = Room(roomID: roomKey,title: title!, description: description!, roomPicutreURL: roomPictureUrl!, longitude: longitude!, latitude: latitude!, dateFrom: dateFrom!, dateTo: dateTo!, owner: owner!)
self.rooms.append(myRooms)
self.tableView.reloadData()
print(snapshot.value)
}
})
You're missing the value in your query:
Database.database().reference()
.child("rooms")
.queryOrdered(byChild: "Owner")
.queryEqual(toValue: "STbz...")
.observeSingleEvent(of: .value, with: { (snapshot) in
See for this and more query operators, the documentation on filtering data.
Mark:- Swift 5
Database.database().reference().child("user")
.queryOrdered(byChild: "UserPhoneNumber") //in which column you want to find
.queryEqual(toValue: "Your phone number or any column value")
.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.childrenCount > 0
{
if let snapShot = snapshot.children.allObjects as? [DataSnapshot] {
//MARK:- User Exist in database
for snap in snapShot{
//MARK:- User auto id for exist user
print(snap.key)
break
}
}
}
else if snapshot.childrenCount == 0
{
//MARK:- User not exist no data found
}
})

Firebase Accessing Snapshot Value Error in Swift 3

I recently upgraded to swift 3 and have been getting an error when trying to access certain things from a snapshot observe event value.
My code:
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let username = snapshot.value!["fullName"] as! String
let homeAddress = snapshot.value!["homeAddress"] as! [Double]
let email = snapshot.value!["email"] as! String
}
The error is around the three variables stated above and states:
Type 'Any' has no subscript members
Any help would be much appreciated
I think that you probably need to cast your snapshot.value as a NSDictionary.
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let username = value?["fullName"] as? String ?? ""
let homeAddress = value?["homeAddress"] as? [Double] ?? []
let email = value?["email"] as? String ?? ""
}
You can take a look on firebase documentation: https://firebase.google.com/docs/database/ios/read-and-write
When Firebase returns data, snapshot.value is of type Any? so as you as the developer can choose to cast it to whatever data type you desire. This means that snapshot.value can be anything from a simple Int to even function types.
Since we know that Firebase Database uses a JSON-tree; pretty much key/value pairing, then you need to cast your snapshot.value to a dictionary as shown below.
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
if let firebaseDic = snapshot.value as? [String: AnyObject] // unwrap it since its an optional
{
let username = firebaseDic["fullName"] as! String
let homeAddress = firebaseDic["homeAddress"] as! [Double]
let email = firebaseDic["email"] as! String
}
else
{
print("Error retrieving FrB data") // snapshot value is nil
}
}

Resources