Grab data saved in Firebase and present it on view controller [closed] - swift

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Edit (I hope this is more specific):
I can't seem to get the data from firebase to show up the page when i run the app:
When a notification is saved under a child node on firebase, an 'objectId' is printed - I want to grab the data under the node that matches this objectId under another node called 'pinion', a snippet of the JSON firebase structure is:
"notification" : {
"Gmg1ojNoBiedFPRNSL4sBZz2gSx2" : {
"-L_xNVcs7f3RhuLAcg7j" : {
"from" : "Gmg1ojNoBiedFPRNSL4sBZz2gSx2",
"objectId" : "-L_xNVcfZavjGFVv6iGs",
"timestamp" : 1552586771,
"type" : "pinion"
},
"pinions" : {
"Gmg1ojNoBiedFPRNSL4sBZz2gSx2" : {
"-L_xNVcfZavjGFVv6iGs" : {
"option A" : "Aaaa",
"option B" : "Cccc",
"question" : "Four",
"selectedId" : "FoFQDAGGX9hntBiBdXYCBHd8yas2",
"uid" : "Gmg1ojNoBiedFPRNSL4sBZz2gSx2"
},
"users" : {
"Gmg1ojNoBiedFPRNSL4sBZz2gSx2" : {
"email" : "eeee#gmail.com",
"fullname" : "Eeee",
"profileImageUrl" : "https://firebasestorage.googleapis.com/v0/b/pinion-4896b.appspot.com/o/profile_image%2FGmg1ojNoBiedFPRNSL4sBZz2gSx2?alt=media&token=209e57ca-b914-4023-8f85-fadfae7b7407",
},
Would appreciate any help and let me know if you need any other information - thank you in advance :)
UPDATE:
It's working for the question and answers but I am getting an error "Unable to infer closure type in the current context" when calling the image:
#IBOutlet weak var senderProfileImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
showImageOfSender()
}
var ref = Database.database().reference()
var userId = "" //this was made equal to the autoId under pinion, under the users ID in another view controller
func showImageOfSender() {
var senderPhoto = [String]()
guard let uid = Auth.auth().currentUser?.uid else {
return
}
let senderId = ref.child("pinions").child(uid).child(userId).child("uid")
ref.child("users").child(senderId).observeSingleEvent(of: .value, with: { snapshot in
//error is in the above line
let senderImage = snapshot.childSnapshot(forPath: "profileImageUrl").value as! String
senderPhoto.append(senderImage)
let senderImageUrl = URL.init(string: senderImage)
self.senderProfileImage.sd_setImage(with: senderImageUrl)
})
}

I think this is what you mean, first import Firebase:
import Firebase
then get the database reference:
class PinionNotificationsViewController: UIViewController {
var ref: DatabaseReference!
...
}
then your function can look like this if you know the UID:
func showQuestionAndAnswers() {
let uid = userId
ref = ref.child("pinions").child(uid)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let optionA = value?["option A"] as! String
let optionB = value?["option B"] as! String
print(optionA) // <- prints: "Bbbb"
print(optionB) // <- prints: "Dddd"
})
}
If you don't know the uid you can use
ref = ref.child("pinions")
ref.observe(.childAdded) { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let optionA = value?["option A"] as! String
// then you can append these values into an array it will go through all of them eg:
self.answersArray.append(optionA) // answers array will contain all optionA values from all children in the database under `"pinions"`
}
This way in my experience would match the database order so in your array all options would be in the order of their children as they are in the database.
Hope this helps!

Related

How to store custom object in Firebase with Swift?

I'm porting an android app and using firebase in android it is possible to save a format in this way.
How can i do this on Swift? I read that i can store only this kind of data
NSString
NSNumber
NSDictionary
NSArray
How can I store the obj in atomic operation?
It's correct to store every field of the user object in separate action?
Firebase on Android
mDatabaseReferences.child("users").child(user.getUuid()).setValue(user)
I generally store objects as dictionaries on firebase. If, within my application, I have a User object, and it has properties as such:
class User {
var username = ""
var email = ""
var userID = ""
var consecutiveDaysLoggedOn = Int()
}
let newUser = User()
newUser.username = "LeviYoder"
newUser.email = "LeviYoder#LeviYoder.com"
newUser.userID = "L735F802847A-"
newUser.consecutiveDaysLoggedOn = 1
I would just store those properties as a dictionary, and write that dictionary to my firebase database:
let userInfoDictionary = ["username" : newUser.username
"email" : newUser.email
"userID" : newUser.userID
"consecutiveDaysLoggedOn" : newUser.consecutiveDaysLoggedOn]
let ref = Database.database().reference.child("UserInfo").child("SpecificUserFolder")
// ref.setValue(userInfoDictionary) { (error:Error?, ref:DatabaseReference) in
ref.setValue(userInfoDictionary, withCompletionBlock: { err, ref in
if let error = err {
print("userInfoDictionary was not saved: \(error.localizedDescription)")
} else {
print("userInfoDictionary saved successfully!")
}
}
Does that address your question?
I come with a little extension used to convert a standard SwiftObject in readable dictionnary for FireStore:
extension Encodable {
var toDictionnary: [String : Any]? {
guard let data = try? JSONEncoder().encode(self) else {
return nil
}
return try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
}
}
For example, in my model:
struct Order: Encodable {
let symbol: String
let shares: Int
let price: Float
let userID: String
}
Called with this line:
let dictionnary = order.toDictionnary
This is the kind of dictionary generated
4 elements
▿ 0 : 2 elements
- key : "symbol"
- value : FP.PAR
▿ 1 : 2 elements
- key : "shares"
- value : 10
▿ 2 : 2 elements
- key : "userID"
- value : fake_id
▿ 3 : 2 elements
- key : "price"
- value : 100
Use
self.ref.child("users").child(user.uid).setValue(["username": username])

Swift child is returning Null when nested or ObserveSingleEvent, returns fine when not nested

I am trying to retrieve a child of a child. the entire snapshotValue returns null. When I retrieve the same data as a child (not nested) it retrieves fine.
I'm Using XCode 10 and Swift 4
To troubleshooting purposes, I have two nodes called 'Promoters'. One at the root and one nested inside a 'Partners' child (preferred). I will remove the top level node when I get the nested node working.
Here is the data structure:
"Partners" : {
"Acts" : [hidden],
"Promoters" : [ null, {
"Cell" : hidden,
"Contact Name" : “hidden”,
"Email" : “hidden”,
"Facebook" : “hidden“,
"Title" : "CHORD Productions"
} ]
},
"Promoters" : {
"chord" : {
"Title" : "Chord Productions"
}
}
This retrieves the data I'm looking for (a list of Titles to populate a picker):
let promotersDB = Database.database().reference().child("Promoters")
promotersDB.observe(.childAdded) { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String, String>
let promoterName = snapshotValue["Title"]!
let promoter = PromoterClass()
promoter.promoterName = promoterName
self.promoterArray.append(promoter)
let isSuccess = true
completion(isSuccess)
}
This returns nil:
let promotersDB = Database.database().reference().child("Partners").child("Promoters")
promotersDB.observe(.childAdded) { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String, String>
let promoterName = snapshotValue["Title"]!
let promoter = PromoterClass()
promoter.promoterName = promoterName
self.promoterArray.append(promoter)
let isSuccess = true
completion(isSuccess)
}
I'd prefer observeSingleEvent, but this also returns nil:
let promotersDB = Database.database().reference().child("Promoters")
promotersDB.observeSingleEvent(of: .value, with: { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String, String>
let promoterName = snapshotValue["Title"]!
let promoter = PromoterClass()
promoter.promoterName = promoterName
self.promoterArray.append(promoter)
let isSuccess = true
completion(isSuccess)
})
The error is:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
**I am using force unwrapping for now to be reviewed at a later date after investigating how much of the data integrity can be done with backend rules :)
Any assistance would be greatly appreciated.
I think firebase usually suggests the Fan Out method when dealing with data trees, so you shouldn't nest array like "Promoters" anyways.
You'll also want to identify each of the Promoters by a uid instead of by their name (incase you have to change their name in the system).
So if you want, try to restructure your data like this:
let uid = Database.database().reference().child("Promoters").childByAutoId()
// uid will be some super long string of random letters and numbers, for example like: 1hjK2SCRV2fhCI0Vv3plGMct3mL2
"Promoters" : {
"1hjK2SCRV2fhCI0Vv3plGMct3mL2" : {
"Title" : "Chord Productions"
}
}
And then when you want to query values within that promoter's branch:
let titleRef = Database.database().reference().child("Promoters").child(uid)
titleRef.observeSingleEvent(of: .value) { (snapshot) in
if let dict = snapshot.value as? [String: AnyObject] {
let promoter = PromoterClass()
promoterName = dict["Title"] as? String
promoter.promoterName = promoterName
}
}

create custom nested tableview cells

I want to create a nested comment section. I am using Firebase as my database. In my app I have a comment section on each post. Logged in users have the ability to comment on a post and their comments can also be commented on, creating a nested effect.
So first I display the comments that were made to the original post. What I want to do is to go through each comment and check to see if there is a comment for that comment and if there is a comment, I want it to display directly under that comment. Just like Instagram or Facebook.
Here is a JSON example of what a nested comment would look like in Firebase
{
"author" : "patient0",
"comments" : {
"comment-487" : {
"author" : "Doctor1",
"comments" : {
"comment-489" : {
"content" : "Your internal capsule in your cerebrum was affected by the stroke",
"id" : "comment-489",
"reply_to" : "comment-487",
"reply_to_type" : "comment"
},
"comment-490" : {
"author" : "Doctor2",
"content" : "Your internal capsule is closely associated with your basal ganglia structures",
"id" : "comment-490",
"reply_to" : "comment-487",
"reply_to_type" : "comment"
}
},
"content" : "I recently had a stroke",
"id" : "comment-487",
"post_id" : "post-1069",
"reply_to" : "post-1069",
"reply_to_type" : "post"
},
"comment-491" : {
"author" : "MedStudent",
"comments" : {
"c_1531642274921" : {
"content" : "Wow! I wonder what cranial nerves were affected due to the hemorrhage",
"id" : "c_1531642274921",
"post_id" : "post-1069",
"pub_time" : 1531642274922,
"reply_to" : "comment-491",
"reply_to_type" : "comment"
}
},
"content" : "The hemorrhage was by the pons and cranial nerve 3 is by the pons, maybe the patient lost the ability to accommodate their eye sight and keep their eyes open.",
"id" : "comment-491",
"num_likes" : 0,
"post_id" : "post-1069",
"reply_to" : "post-1069",
"reply_to_type" : "post"
}
},
"content" : "I have a headache",
"id" : "post-1069",
"num_comments" : 5,
"title" : "I have a headache, should I go to the hospital",
}
As of now I am able to get the inital comments to print (the comments made directly to the post)
func loadComments(){
Database.database().reference().child("main").child("posts").child(postID!).child("comments").queryOrdered(byChild: "id").observeSingleEvent(of: .value, with: { (snapshot:DataSnapshot) in
if let postsDictionary = snapshot .value as? [String: AnyObject] {
for testingkey in postsDictionary.keys {
Database.database().reference().child("main").child("posts").child(self.postID!).child("comments").child(testingkey).child("comments").queryOrdered(byChild: "post_id").observeSingleEvent(of: .value, with: { (snapshot:DataSnapshot) in
if let postsDictionary = snapshot .value as? [String: AnyObject] {
for post in postsDictionary {
}
DispatchQueue.main.async(execute: {
self.TableView.reloadData()
})
}
})
}
for post in postsDictionary {
//main comments
self.Comments.add(post.value)
}
DispatchQueue.main.async(execute: {
self.TableView.reloadData()
})
}
})
}
I just don't know how to go through each post to check to see if there is a comment associated with it. Also if there is a comment associated with the original comment, I want it to print out in a custom cell.
I'd create a class or struct for comment, with an array of comments as a property.
class Comment {
let id: String
let author: String
var content: String
var comments: [Comment]
}
Then I'd create a TopLevelComment class as a subclass of Comment
class TopLevelComment: Comment {
// Whatever special properties you want your top level comments to have
}
You can now check if a comment is replying to a post or a comment by simply using
comment is TopLevelComment
Then you should restructure your database appropriately so you can cast it to the Comment class
For your tableView, I'd use a tableview for each top level comment, maybe even a section for each.
You can create an element for comment elements .
var commentElements = [CustomStruct]()
After creating Custom Element pull the variables from Firebase and save .
if let postsDictionary = snapshot .value as? [String: AnyObject] {
guard let comment = postsDictionary["comments"] as? NSArray else { return }
for com in comment {
guard let commentObject = com as? [String:Any] else { return }
let id = commentObject["id"]
let type = commentObject["reply_to_type"]
let replyTo = commentObject["reply_to"]
let content = commentObject["content"]
let element = CustomStruct(id:id , type:type , ....)
commentElements.append(element)
}
for post in postsDictionary {
}
DispatchQueue.main.async(execute: {
self.TableView.reloadData()
})
}
After pulling all elements , you may group based on comment Id . And you can show with Section in TableView.You sort the first element "reply_to_type" : "post"
As per your question, I believe that you are having difficulty in figuring out how to parse the JSON to a format (or view model) which can be used to display your posts and comments.
You can use the following model sample (with reworks or tweaks of your own, if needed) to parse and organize your posts and it's comments.
class Post {
var author: String?
var comments: [Post] = []
var content: String?
var id: String?
var numComments: Int?
var title: String?
init(dict: [String: AnyObject]?) {
author = dict?["author"] as? String
content = dict?["content"] as? String
id = dict?["id"] as? String
numComments = dict?["num_comments"] as? Int
title = dict?["title"] as? String
if let commentsDict = dict?["comments"] as? [String: AnyObject] {
// Sort the comments based on the id which seems to be appended to the comment key.
let commentIds = commentsDict.keys.sorted()
for id in commentIds {
let comment = commentsDict[id] as? [String : AnyObject]
comments.append(Post(dict: comment))
}
}
}
}
Usage:
//
// postDict is your dictionary object corresponding to one post.
//
// Assign your post's dictionary item to this variable.
//
var postDict: [String: AnyObject]?
// "Post" object which has recursive comments within up to any number of levels.
// Comments are also using the same model object.
// If you want to use another, you can create one with the corresponding elements.
let post = Post(dict: postDict)
P.S: The JSON structure looks to be not of a unique structure. You might want to rework on this structure to make sure that your content gets mapped neatly.

Crash while retrieving data from Firebase [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
My Code
let ref = Database.database().reference().child("PostInfo")
let query = ref.queryOrdered(byChild: "post_title").queryEqual(toValue: self.retrieve_title)
query.observeSingleEvent(of: .value) { (snapshot) in
print((snapshot.childSnapshot(forPath: "status").value as? String)!)
}
}
jSon Data
{"PostInfo":{
"-KyjkkEAZeHLjdRLg20w" : {
"postImage" : "https://firebasestorage.googleapis.com/v0/b/hobbyquest-ee18d.appspot.com/o/8C40BA04-6D8D-4A23-B8BB-E1B3AC64E66F.png?alt=media&token=3f0f10e3-a64b-4187-9259-3c25bfc4a9e5",
"post_title" : "hahahahah",
"status" : "a banana an",
"threadForHobby" : "Bowling",
"userID" : "ccuvHt6feYVIO6GUXKo3OpO6VUn2"}
}
I am trying to get the status data from firebase but the app keeps crashing. Please help!
The problem is this line
(snapshot.childSnapshot(forPath: "status").value as? String)!
Your code is reading the data by .value.
.value returns ALL nodes within the given node and you will need to iterate over them. For example. Suppose our database looks like the following and you are querying for posts with a post_title of title_0
PostInfo
post_0
postImage = "www.thing.com"
status = "status_0"
post_title = "title_0"
post_1
postImage = "www.yipee.com"
status = "status_1"
post_title = "title_1"
post_2
postImage = "www.dude.com"
status = "status_2"
post_title = "title_0"
When running your query, both post_0 and post_2 will be returned because they both have title_0
You would need to iterate over the snapshot to get the results.
let ref = self.ref.child("PostInfo")
let query = ref.queryOrdered(byChild: "post_title").queryEqual(toValue: "title_0")
query.observeSingleEvent(of: .value) { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let x = (snap.childSnapshot(forPath: "status").value as? String)!
print(x)
}
}
If you notice - your line of code works in this scenario because it's examining each child as a separate snapshot.
On the other hand, if you only want to return the first match, you can use .childAdded, which will return just an individual node:
let ref = self.ref.child("PostInfo")
let query = ref.queryOrdered(byChild: "post_title").queryEqual(toValue: "title_0")
query.observeSingleEvent(of: .childAdded) { (snapshot) in
let x = (snapshot.childSnapshot(forPath: "status").value as? String)!
print(x)
}
I don't know why but you could do it a different way but changing the layout of your data.
The data would be like this:
{"PostInfo":{
"searchidentifier" : { //whatever identifier you want, I think you're trying to use the post title
"object" : {
"postImage" : "https://firebasestorage.googleapis.com/v0/b/hobbyquest-ee18d.appspot.com/o/8C40BA04-6D8D-4A23-B8BB-E1B3AC64E66F.png?alt=media&token=3f0f10e3-a64b-4187-9259-3c25bfc4a9e5",
"post_title" : "hahahahah",
"status" : "a banana an",
"threadForHobby" : "Bowling",
"userID" : "ccuvHt6feYVIO6GUXKo3OpO6VUn2"}
}
}
And you would retrieve your data like this:
let ref = Database.database().reference().child("PostInfo").child("\(self.retrieve_title)")
ref.observe(.value, with: { (snapshot) in
if snapshot.childrenCount > 0 {
for classes in snapshot.children.allObjects as![FIRDataSnapshot] {
let classesObject = classes.value as? [String: AnyObject]
let postImage = classesObject?["postimage"]
//Retrieve all the other objects here as well
}
}
})

How to retrieve a value from dictionary in Swift 3

I have this function that fetch users from FireBase and convert them in Dictionary:
let leaderBoardDB = FIRDatabase.database().reference().child("scores1").queryOrderedByValue().queryLimited(toLast: 5)
leaderBoardDB.observe( .value, with: { (snapshot) in
print("scores scores", snapshot)
if let dictionary = snapshot.value as? [String: Any] {
for playa in dictionary {
let player = Player()
print("plaaaaayyyyyaaaaa", playa)
print("plaaaaayyyyyaaaaa key", playa.key)
print("plaaaaayyyyyaaaaa.value", playa.value)
player.id = playa.key
print(playa.key["name"])
}
}
}, withCancel: nil)
}
and I get this result:
plaaaaayyyyyaaaaa ("inovoID", {
name = Tatiana;
points = 6; }) plaaaaayyyyyaaaaa key inovoID plaaaaayyyyyaaaaa.value {
name = Tatiana;
points = 6; } aaaa i id Optional("inovoID")
the problem is that i can't obtain the name and the points of the user. when i try it with:
print(playa.key["name"])
it gaves me this error:
Cannot subscript a value of type 'String' with an index of type 'String'
can anyone help me with this, please?
Since your JSON is
"inovoID" : { "name" : "Tatiana", "points" : 6 }
playa.key is "inovoID"
playa.value is { "name" : "Tatiana", "points" : 6 }
The key is String and cannot be subscripted. That's what the error says.
You need to subscribe the value and safely cast the type to help the compiler.
if let person = playa.value as? [String:Any] {
print(person["name"] as! String)
}
I think you're looking for:
player.name = dictionary["name"] as? String
You don't need to iterate through the dictionary to access it's values. If you're looking for the value of a key, just get it.