Fetch data from multiple node in Firebase in Swift












1















I built my app to have news feed like Facebook. My problem is that I don't know how to fetch child images in Post and show it in a collectionView. Please show me how to do it. Appreciate any help.



Here is the db structure:



Posts
d7j3bWMluvZ6VH4tctQ7B63dU4u1:
20181112101928:
avatar: "https://platform-lookaside.fbsbx.com/platform/p..."
content: "Funny image"
images:
-LR4vaEIggkGekc-5ZME:
"https://firebasestorage.googleapis.com/v0/b/hon..."
-LR4vaENC-IsePibQYxY:
"https://firebasestorage.googleapis.com/v0/b/hon..."
name: "Thành Trung"
time: 1541992768776.3628
type: "Funny"


Here is my code:



   func getDataFromPostFirebase() {
let getPostData = databaseReference.child("Posts")
getPostData.observe(.childAdded) { (snapshot) in
getPostData.child(snapshot.key).observe(.childAdded, with: { (snapshot1) in
getPostData.child(snapshot.key).child(snapshot1.key).observe(.value, with: { (snapshot2) in
self.arrayImageUrl = [String]()
if let dict = snapshot2.value as? [String : Any] {
guard let avatar = dict["avatar"] as? String else {return}
guard let content = dict["content"] as? String else {return}
guard let name = dict["name"] as? String else {return}
guard let time = dict["time"] as? Double else {return}
guard let type = dict["type"] as? String else {return}
if let images = dict["images"] as? [String : String] {
for image in images.values {
self.arrayImageUrl.append(image)
}
let newPost = Post(avatarString: avatar, contentString: content, nameString: name, timeDouble: time, typeString: type)
self.arrayPost.append(newPost)
DispatchQueue.main.async {
self.feedTableView.reloadData()
}
} else {
let newPost = Post(avatarString: avatar, contentString: content, nameString: name, timeDouble: time, typeString: type)
self.arrayPost.append(newPost)
DispatchQueue.main.async {
self.feedTableView.reloadData()
}
}
}
})
})
}
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayImageUrl.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! TrangChu_CollectionViewCell

cell.imgContent.layer.cornerRadius = CGFloat(8)
cell.imgContent.clipsToBounds = true
cell.imgContent.layer.borderWidth = 2
cell.imgContent.layer.borderColor = #colorLiteral(red: 0.4756349325, green: 0.4756467342, blue: 0.4756404161, alpha: 1)

let url = URL(string: arrayImageUrl[indexPath.row])
cell.imgContent.sd_setImage(with: url, completed: nil)

return cell
}


Model object



import Foundation

class Post {
var avatar : String
var content : String
var images : [String]?
var name : String
var time : Double
var type : String

init(avatarString : String, contentString : String, nameString : String, timeDouble : Double, typeString : String) {
avatar = avatarString
content = contentString
// images = imagesString
name = nameString
time = timeDouble
type = typeString
}
}









share|improve this question

























  • I guess you need to loop your images node as you have multiple data in it.

    – ManishPrajapati
    Nov 12 '18 at 9:02











  • thanks for your comment, i loop it already but the images show wrong in collectionView

    – Trung Nguyen
    Nov 12 '18 at 9:06
















1















I built my app to have news feed like Facebook. My problem is that I don't know how to fetch child images in Post and show it in a collectionView. Please show me how to do it. Appreciate any help.



Here is the db structure:



Posts
d7j3bWMluvZ6VH4tctQ7B63dU4u1:
20181112101928:
avatar: "https://platform-lookaside.fbsbx.com/platform/p..."
content: "Funny image"
images:
-LR4vaEIggkGekc-5ZME:
"https://firebasestorage.googleapis.com/v0/b/hon..."
-LR4vaENC-IsePibQYxY:
"https://firebasestorage.googleapis.com/v0/b/hon..."
name: "Thành Trung"
time: 1541992768776.3628
type: "Funny"


Here is my code:



   func getDataFromPostFirebase() {
let getPostData = databaseReference.child("Posts")
getPostData.observe(.childAdded) { (snapshot) in
getPostData.child(snapshot.key).observe(.childAdded, with: { (snapshot1) in
getPostData.child(snapshot.key).child(snapshot1.key).observe(.value, with: { (snapshot2) in
self.arrayImageUrl = [String]()
if let dict = snapshot2.value as? [String : Any] {
guard let avatar = dict["avatar"] as? String else {return}
guard let content = dict["content"] as? String else {return}
guard let name = dict["name"] as? String else {return}
guard let time = dict["time"] as? Double else {return}
guard let type = dict["type"] as? String else {return}
if let images = dict["images"] as? [String : String] {
for image in images.values {
self.arrayImageUrl.append(image)
}
let newPost = Post(avatarString: avatar, contentString: content, nameString: name, timeDouble: time, typeString: type)
self.arrayPost.append(newPost)
DispatchQueue.main.async {
self.feedTableView.reloadData()
}
} else {
let newPost = Post(avatarString: avatar, contentString: content, nameString: name, timeDouble: time, typeString: type)
self.arrayPost.append(newPost)
DispatchQueue.main.async {
self.feedTableView.reloadData()
}
}
}
})
})
}
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayImageUrl.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! TrangChu_CollectionViewCell

cell.imgContent.layer.cornerRadius = CGFloat(8)
cell.imgContent.clipsToBounds = true
cell.imgContent.layer.borderWidth = 2
cell.imgContent.layer.borderColor = #colorLiteral(red: 0.4756349325, green: 0.4756467342, blue: 0.4756404161, alpha: 1)

let url = URL(string: arrayImageUrl[indexPath.row])
cell.imgContent.sd_setImage(with: url, completed: nil)

return cell
}


Model object



import Foundation

class Post {
var avatar : String
var content : String
var images : [String]?
var name : String
var time : Double
var type : String

init(avatarString : String, contentString : String, nameString : String, timeDouble : Double, typeString : String) {
avatar = avatarString
content = contentString
// images = imagesString
name = nameString
time = timeDouble
type = typeString
}
}









share|improve this question

























  • I guess you need to loop your images node as you have multiple data in it.

    – ManishPrajapati
    Nov 12 '18 at 9:02











  • thanks for your comment, i loop it already but the images show wrong in collectionView

    – Trung Nguyen
    Nov 12 '18 at 9:06














1












1








1








I built my app to have news feed like Facebook. My problem is that I don't know how to fetch child images in Post and show it in a collectionView. Please show me how to do it. Appreciate any help.



Here is the db structure:



Posts
d7j3bWMluvZ6VH4tctQ7B63dU4u1:
20181112101928:
avatar: "https://platform-lookaside.fbsbx.com/platform/p..."
content: "Funny image"
images:
-LR4vaEIggkGekc-5ZME:
"https://firebasestorage.googleapis.com/v0/b/hon..."
-LR4vaENC-IsePibQYxY:
"https://firebasestorage.googleapis.com/v0/b/hon..."
name: "Thành Trung"
time: 1541992768776.3628
type: "Funny"


Here is my code:



   func getDataFromPostFirebase() {
let getPostData = databaseReference.child("Posts")
getPostData.observe(.childAdded) { (snapshot) in
getPostData.child(snapshot.key).observe(.childAdded, with: { (snapshot1) in
getPostData.child(snapshot.key).child(snapshot1.key).observe(.value, with: { (snapshot2) in
self.arrayImageUrl = [String]()
if let dict = snapshot2.value as? [String : Any] {
guard let avatar = dict["avatar"] as? String else {return}
guard let content = dict["content"] as? String else {return}
guard let name = dict["name"] as? String else {return}
guard let time = dict["time"] as? Double else {return}
guard let type = dict["type"] as? String else {return}
if let images = dict["images"] as? [String : String] {
for image in images.values {
self.arrayImageUrl.append(image)
}
let newPost = Post(avatarString: avatar, contentString: content, nameString: name, timeDouble: time, typeString: type)
self.arrayPost.append(newPost)
DispatchQueue.main.async {
self.feedTableView.reloadData()
}
} else {
let newPost = Post(avatarString: avatar, contentString: content, nameString: name, timeDouble: time, typeString: type)
self.arrayPost.append(newPost)
DispatchQueue.main.async {
self.feedTableView.reloadData()
}
}
}
})
})
}
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayImageUrl.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! TrangChu_CollectionViewCell

cell.imgContent.layer.cornerRadius = CGFloat(8)
cell.imgContent.clipsToBounds = true
cell.imgContent.layer.borderWidth = 2
cell.imgContent.layer.borderColor = #colorLiteral(red: 0.4756349325, green: 0.4756467342, blue: 0.4756404161, alpha: 1)

let url = URL(string: arrayImageUrl[indexPath.row])
cell.imgContent.sd_setImage(with: url, completed: nil)

return cell
}


Model object



import Foundation

class Post {
var avatar : String
var content : String
var images : [String]?
var name : String
var time : Double
var type : String

init(avatarString : String, contentString : String, nameString : String, timeDouble : Double, typeString : String) {
avatar = avatarString
content = contentString
// images = imagesString
name = nameString
time = timeDouble
type = typeString
}
}









share|improve this question
















I built my app to have news feed like Facebook. My problem is that I don't know how to fetch child images in Post and show it in a collectionView. Please show me how to do it. Appreciate any help.



Here is the db structure:



Posts
d7j3bWMluvZ6VH4tctQ7B63dU4u1:
20181112101928:
avatar: "https://platform-lookaside.fbsbx.com/platform/p..."
content: "Funny image"
images:
-LR4vaEIggkGekc-5ZME:
"https://firebasestorage.googleapis.com/v0/b/hon..."
-LR4vaENC-IsePibQYxY:
"https://firebasestorage.googleapis.com/v0/b/hon..."
name: "Thành Trung"
time: 1541992768776.3628
type: "Funny"


Here is my code:



   func getDataFromPostFirebase() {
let getPostData = databaseReference.child("Posts")
getPostData.observe(.childAdded) { (snapshot) in
getPostData.child(snapshot.key).observe(.childAdded, with: { (snapshot1) in
getPostData.child(snapshot.key).child(snapshot1.key).observe(.value, with: { (snapshot2) in
self.arrayImageUrl = [String]()
if let dict = snapshot2.value as? [String : Any] {
guard let avatar = dict["avatar"] as? String else {return}
guard let content = dict["content"] as? String else {return}
guard let name = dict["name"] as? String else {return}
guard let time = dict["time"] as? Double else {return}
guard let type = dict["type"] as? String else {return}
if let images = dict["images"] as? [String : String] {
for image in images.values {
self.arrayImageUrl.append(image)
}
let newPost = Post(avatarString: avatar, contentString: content, nameString: name, timeDouble: time, typeString: type)
self.arrayPost.append(newPost)
DispatchQueue.main.async {
self.feedTableView.reloadData()
}
} else {
let newPost = Post(avatarString: avatar, contentString: content, nameString: name, timeDouble: time, typeString: type)
self.arrayPost.append(newPost)
DispatchQueue.main.async {
self.feedTableView.reloadData()
}
}
}
})
})
}
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayImageUrl.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! TrangChu_CollectionViewCell

cell.imgContent.layer.cornerRadius = CGFloat(8)
cell.imgContent.clipsToBounds = true
cell.imgContent.layer.borderWidth = 2
cell.imgContent.layer.borderColor = #colorLiteral(red: 0.4756349325, green: 0.4756467342, blue: 0.4756404161, alpha: 1)

let url = URL(string: arrayImageUrl[indexPath.row])
cell.imgContent.sd_setImage(with: url, completed: nil)

return cell
}


Model object



import Foundation

class Post {
var avatar : String
var content : String
var images : [String]?
var name : String
var time : Double
var type : String

init(avatarString : String, contentString : String, nameString : String, timeDouble : Double, typeString : String) {
avatar = avatarString
content = contentString
// images = imagesString
name = nameString
time = timeDouble
type = typeString
}
}






swift firebase firebase-realtime-database






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 3:54







Trung Nguyen

















asked Nov 12 '18 at 8:31









Trung NguyenTrung Nguyen

427




427













  • I guess you need to loop your images node as you have multiple data in it.

    – ManishPrajapati
    Nov 12 '18 at 9:02











  • thanks for your comment, i loop it already but the images show wrong in collectionView

    – Trung Nguyen
    Nov 12 '18 at 9:06



















  • I guess you need to loop your images node as you have multiple data in it.

    – ManishPrajapati
    Nov 12 '18 at 9:02











  • thanks for your comment, i loop it already but the images show wrong in collectionView

    – Trung Nguyen
    Nov 12 '18 at 9:06

















I guess you need to loop your images node as you have multiple data in it.

– ManishPrajapati
Nov 12 '18 at 9:02





I guess you need to loop your images node as you have multiple data in it.

– ManishPrajapati
Nov 12 '18 at 9:02













thanks for your comment, i loop it already but the images show wrong in collectionView

– Trung Nguyen
Nov 12 '18 at 9:06





thanks for your comment, i loop it already but the images show wrong in collectionView

– Trung Nguyen
Nov 12 '18 at 9:06












3 Answers
3






active

oldest

votes


















2














As what I've said your db is not well structured. I suggest you re structure it like this.



Posts
d7j3bWMluvZ6VH4tctQ7B63dU4u1:
avatar: "https://platform-lookaside.fbsbx.com/platform/p..."
content: "Funny image"
images:
-LR4vaEIggkGekc-5ZME: "https://firebasestorage.googleapis.com/v0/b/hon..."
-LR4vaENC-IsePibQYxY: "https://firebasestorage.googleapis.com/v0/b/hon..."
name: "Thành Trung"
time: 1541992768776.3628
type: "Funny"
timestamp: 1540276959924


I removed the timestamp node and transferred it along the children node. Now you can fetch the posts with this.



ref.child("Posts").observe(.childAdded) { (snapshot) in
var post = Post()

let val = snapshot.value as! [String: Any]
post.name = val["name"] as? String

self.ref.child("Posts").child(snapshot.key).child("images").observeSingleEvent(of: .value, with: { (snap) in
post.imagesString = [String]()
for image in snap.children.allObjects as! [DataSnapshot] {
post.imagesString?.append(image.value as! String)
print("images (image.value)")
}

list.append(post)
print("post (post)")
})


If you want to order the posts you can achieve it using queryOrderedByChild("timestamp")






share|improve this answer
























  • i change the db structure already, but images from all post append in array images so each post show all of images from other post. please help me how to fix this

    – Trung Nguyen
    Nov 14 '18 at 2:42











  • the array for collectionView to show image may be wrong. help me how to fix it please

    – Trung Nguyen
    Nov 14 '18 at 3:10











  • Please update the code you've done so far. @TrungNguyen

    – elbert rivas
    Nov 14 '18 at 3:30











  • I update already @elbert rivas. I fetch the image success but I think the array of collectionView have wrong data. It only shows images of last post. please have a look

    – Trung Nguyen
    Nov 14 '18 at 3:37













  • Update your db structure also @TrungNguyen

    – elbert rivas
    Nov 14 '18 at 3:49





















0














Add this to access your images:



guard let images = dict["images"] as? [[String: Any]] { return }
let imagesString: [String] =
for imageDict in images {
for key in imageDict.keys {
if let imageName = imageDict[key] as? String else {
// here you access your image as you want
imagesString.append(imageName)
}
}
}


Then when creating the post object you use imagesString that we created:



let newPost = Post(avatarString: avatar, contentString: content, imagesString: imagesString, nameString: name, timeDouble: time, typeString: type)





share|improve this answer


























  • it doesn't work, show the error "Cannot subscript a value of type '[String : String]' with an index of type 'Dictionary<String, String>.Keys'"

    – Trung Nguyen
    Nov 12 '18 at 14:13











  • I fixed the error, check the edited answer

    – DionizB
    Nov 12 '18 at 14:46











  • i want to append it to array model Post. So how can i do that. The image already showed in collection view but it duplicate. How can i fix that

    – Trung Nguyen
    Nov 12 '18 at 14:52











  • I edited the answer again

    – DionizB
    Nov 12 '18 at 14:56











  • still doesn't work, please help me

    – Trung Nguyen
    Nov 12 '18 at 15:10



















0














You can fetch the images values using this



ref.child("Posts").observe(.childAdded) { (snapshot) in

self.ref.child("Posts").child(snapshot.key).observe(.childAdded, with: { (snapshot1) in
self.ref.child("Posts").child(snapshot.key).child(snapshot1.key).child("images").observe(.childAdded, with: { (snap) in
let post = new Post()
for rest in snap.children.allObjects as! [DataSnapshot] {
//append images
post.imagesString.append(rest.value)
}


post.avatarString = snapshot1.value["avatar"] as? String
...
})
})


I suggest you change the structure of your db because its nested. Refer here






share|improve this answer


























  • how can i fetch image into Post array, and show it to collectionView. Please help me

    – Trung Nguyen
    Nov 12 '18 at 14:26













  • I edited the code. Try if it will work

    – elbert rivas
    Nov 12 '18 at 15:41













  • i will try it now. Thanks bro for your helping

    – Trung Nguyen
    Nov 13 '18 at 1:43











  • images from all post append in array images so each post show all of images from other post. please help me how to fix this

    – Trung Nguyen
    Nov 13 '18 at 1:56











  • Check my new answer @TrungNguyen

    – elbert rivas
    Nov 13 '18 at 3:15











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53258349%2ffetch-data-from-multiple-node-in-firebase-in-swift%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














As what I've said your db is not well structured. I suggest you re structure it like this.



Posts
d7j3bWMluvZ6VH4tctQ7B63dU4u1:
avatar: "https://platform-lookaside.fbsbx.com/platform/p..."
content: "Funny image"
images:
-LR4vaEIggkGekc-5ZME: "https://firebasestorage.googleapis.com/v0/b/hon..."
-LR4vaENC-IsePibQYxY: "https://firebasestorage.googleapis.com/v0/b/hon..."
name: "Thành Trung"
time: 1541992768776.3628
type: "Funny"
timestamp: 1540276959924


I removed the timestamp node and transferred it along the children node. Now you can fetch the posts with this.



ref.child("Posts").observe(.childAdded) { (snapshot) in
var post = Post()

let val = snapshot.value as! [String: Any]
post.name = val["name"] as? String

self.ref.child("Posts").child(snapshot.key).child("images").observeSingleEvent(of: .value, with: { (snap) in
post.imagesString = [String]()
for image in snap.children.allObjects as! [DataSnapshot] {
post.imagesString?.append(image.value as! String)
print("images (image.value)")
}

list.append(post)
print("post (post)")
})


If you want to order the posts you can achieve it using queryOrderedByChild("timestamp")






share|improve this answer
























  • i change the db structure already, but images from all post append in array images so each post show all of images from other post. please help me how to fix this

    – Trung Nguyen
    Nov 14 '18 at 2:42











  • the array for collectionView to show image may be wrong. help me how to fix it please

    – Trung Nguyen
    Nov 14 '18 at 3:10











  • Please update the code you've done so far. @TrungNguyen

    – elbert rivas
    Nov 14 '18 at 3:30











  • I update already @elbert rivas. I fetch the image success but I think the array of collectionView have wrong data. It only shows images of last post. please have a look

    – Trung Nguyen
    Nov 14 '18 at 3:37













  • Update your db structure also @TrungNguyen

    – elbert rivas
    Nov 14 '18 at 3:49


















2














As what I've said your db is not well structured. I suggest you re structure it like this.



Posts
d7j3bWMluvZ6VH4tctQ7B63dU4u1:
avatar: "https://platform-lookaside.fbsbx.com/platform/p..."
content: "Funny image"
images:
-LR4vaEIggkGekc-5ZME: "https://firebasestorage.googleapis.com/v0/b/hon..."
-LR4vaENC-IsePibQYxY: "https://firebasestorage.googleapis.com/v0/b/hon..."
name: "Thành Trung"
time: 1541992768776.3628
type: "Funny"
timestamp: 1540276959924


I removed the timestamp node and transferred it along the children node. Now you can fetch the posts with this.



ref.child("Posts").observe(.childAdded) { (snapshot) in
var post = Post()

let val = snapshot.value as! [String: Any]
post.name = val["name"] as? String

self.ref.child("Posts").child(snapshot.key).child("images").observeSingleEvent(of: .value, with: { (snap) in
post.imagesString = [String]()
for image in snap.children.allObjects as! [DataSnapshot] {
post.imagesString?.append(image.value as! String)
print("images (image.value)")
}

list.append(post)
print("post (post)")
})


If you want to order the posts you can achieve it using queryOrderedByChild("timestamp")






share|improve this answer
























  • i change the db structure already, but images from all post append in array images so each post show all of images from other post. please help me how to fix this

    – Trung Nguyen
    Nov 14 '18 at 2:42











  • the array for collectionView to show image may be wrong. help me how to fix it please

    – Trung Nguyen
    Nov 14 '18 at 3:10











  • Please update the code you've done so far. @TrungNguyen

    – elbert rivas
    Nov 14 '18 at 3:30











  • I update already @elbert rivas. I fetch the image success but I think the array of collectionView have wrong data. It only shows images of last post. please have a look

    – Trung Nguyen
    Nov 14 '18 at 3:37













  • Update your db structure also @TrungNguyen

    – elbert rivas
    Nov 14 '18 at 3:49
















2












2








2







As what I've said your db is not well structured. I suggest you re structure it like this.



Posts
d7j3bWMluvZ6VH4tctQ7B63dU4u1:
avatar: "https://platform-lookaside.fbsbx.com/platform/p..."
content: "Funny image"
images:
-LR4vaEIggkGekc-5ZME: "https://firebasestorage.googleapis.com/v0/b/hon..."
-LR4vaENC-IsePibQYxY: "https://firebasestorage.googleapis.com/v0/b/hon..."
name: "Thành Trung"
time: 1541992768776.3628
type: "Funny"
timestamp: 1540276959924


I removed the timestamp node and transferred it along the children node. Now you can fetch the posts with this.



ref.child("Posts").observe(.childAdded) { (snapshot) in
var post = Post()

let val = snapshot.value as! [String: Any]
post.name = val["name"] as? String

self.ref.child("Posts").child(snapshot.key).child("images").observeSingleEvent(of: .value, with: { (snap) in
post.imagesString = [String]()
for image in snap.children.allObjects as! [DataSnapshot] {
post.imagesString?.append(image.value as! String)
print("images (image.value)")
}

list.append(post)
print("post (post)")
})


If you want to order the posts you can achieve it using queryOrderedByChild("timestamp")






share|improve this answer













As what I've said your db is not well structured. I suggest you re structure it like this.



Posts
d7j3bWMluvZ6VH4tctQ7B63dU4u1:
avatar: "https://platform-lookaside.fbsbx.com/platform/p..."
content: "Funny image"
images:
-LR4vaEIggkGekc-5ZME: "https://firebasestorage.googleapis.com/v0/b/hon..."
-LR4vaENC-IsePibQYxY: "https://firebasestorage.googleapis.com/v0/b/hon..."
name: "Thành Trung"
time: 1541992768776.3628
type: "Funny"
timestamp: 1540276959924


I removed the timestamp node and transferred it along the children node. Now you can fetch the posts with this.



ref.child("Posts").observe(.childAdded) { (snapshot) in
var post = Post()

let val = snapshot.value as! [String: Any]
post.name = val["name"] as? String

self.ref.child("Posts").child(snapshot.key).child("images").observeSingleEvent(of: .value, with: { (snap) in
post.imagesString = [String]()
for image in snap.children.allObjects as! [DataSnapshot] {
post.imagesString?.append(image.value as! String)
print("images (image.value)")
}

list.append(post)
print("post (post)")
})


If you want to order the posts you can achieve it using queryOrderedByChild("timestamp")







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 13 '18 at 3:14









elbert rivaselbert rivas

332210




332210













  • i change the db structure already, but images from all post append in array images so each post show all of images from other post. please help me how to fix this

    – Trung Nguyen
    Nov 14 '18 at 2:42











  • the array for collectionView to show image may be wrong. help me how to fix it please

    – Trung Nguyen
    Nov 14 '18 at 3:10











  • Please update the code you've done so far. @TrungNguyen

    – elbert rivas
    Nov 14 '18 at 3:30











  • I update already @elbert rivas. I fetch the image success but I think the array of collectionView have wrong data. It only shows images of last post. please have a look

    – Trung Nguyen
    Nov 14 '18 at 3:37













  • Update your db structure also @TrungNguyen

    – elbert rivas
    Nov 14 '18 at 3:49





















  • i change the db structure already, but images from all post append in array images so each post show all of images from other post. please help me how to fix this

    – Trung Nguyen
    Nov 14 '18 at 2:42











  • the array for collectionView to show image may be wrong. help me how to fix it please

    – Trung Nguyen
    Nov 14 '18 at 3:10











  • Please update the code you've done so far. @TrungNguyen

    – elbert rivas
    Nov 14 '18 at 3:30











  • I update already @elbert rivas. I fetch the image success but I think the array of collectionView have wrong data. It only shows images of last post. please have a look

    – Trung Nguyen
    Nov 14 '18 at 3:37













  • Update your db structure also @TrungNguyen

    – elbert rivas
    Nov 14 '18 at 3:49



















i change the db structure already, but images from all post append in array images so each post show all of images from other post. please help me how to fix this

– Trung Nguyen
Nov 14 '18 at 2:42





i change the db structure already, but images from all post append in array images so each post show all of images from other post. please help me how to fix this

– Trung Nguyen
Nov 14 '18 at 2:42













the array for collectionView to show image may be wrong. help me how to fix it please

– Trung Nguyen
Nov 14 '18 at 3:10





the array for collectionView to show image may be wrong. help me how to fix it please

– Trung Nguyen
Nov 14 '18 at 3:10













Please update the code you've done so far. @TrungNguyen

– elbert rivas
Nov 14 '18 at 3:30





Please update the code you've done so far. @TrungNguyen

– elbert rivas
Nov 14 '18 at 3:30













I update already @elbert rivas. I fetch the image success but I think the array of collectionView have wrong data. It only shows images of last post. please have a look

– Trung Nguyen
Nov 14 '18 at 3:37







I update already @elbert rivas. I fetch the image success but I think the array of collectionView have wrong data. It only shows images of last post. please have a look

– Trung Nguyen
Nov 14 '18 at 3:37















Update your db structure also @TrungNguyen

– elbert rivas
Nov 14 '18 at 3:49







Update your db structure also @TrungNguyen

– elbert rivas
Nov 14 '18 at 3:49















0














Add this to access your images:



guard let images = dict["images"] as? [[String: Any]] { return }
let imagesString: [String] =
for imageDict in images {
for key in imageDict.keys {
if let imageName = imageDict[key] as? String else {
// here you access your image as you want
imagesString.append(imageName)
}
}
}


Then when creating the post object you use imagesString that we created:



let newPost = Post(avatarString: avatar, contentString: content, imagesString: imagesString, nameString: name, timeDouble: time, typeString: type)





share|improve this answer


























  • it doesn't work, show the error "Cannot subscript a value of type '[String : String]' with an index of type 'Dictionary<String, String>.Keys'"

    – Trung Nguyen
    Nov 12 '18 at 14:13











  • I fixed the error, check the edited answer

    – DionizB
    Nov 12 '18 at 14:46











  • i want to append it to array model Post. So how can i do that. The image already showed in collection view but it duplicate. How can i fix that

    – Trung Nguyen
    Nov 12 '18 at 14:52











  • I edited the answer again

    – DionizB
    Nov 12 '18 at 14:56











  • still doesn't work, please help me

    – Trung Nguyen
    Nov 12 '18 at 15:10
















0














Add this to access your images:



guard let images = dict["images"] as? [[String: Any]] { return }
let imagesString: [String] =
for imageDict in images {
for key in imageDict.keys {
if let imageName = imageDict[key] as? String else {
// here you access your image as you want
imagesString.append(imageName)
}
}
}


Then when creating the post object you use imagesString that we created:



let newPost = Post(avatarString: avatar, contentString: content, imagesString: imagesString, nameString: name, timeDouble: time, typeString: type)





share|improve this answer


























  • it doesn't work, show the error "Cannot subscript a value of type '[String : String]' with an index of type 'Dictionary<String, String>.Keys'"

    – Trung Nguyen
    Nov 12 '18 at 14:13











  • I fixed the error, check the edited answer

    – DionizB
    Nov 12 '18 at 14:46











  • i want to append it to array model Post. So how can i do that. The image already showed in collection view but it duplicate. How can i fix that

    – Trung Nguyen
    Nov 12 '18 at 14:52











  • I edited the answer again

    – DionizB
    Nov 12 '18 at 14:56











  • still doesn't work, please help me

    – Trung Nguyen
    Nov 12 '18 at 15:10














0












0








0







Add this to access your images:



guard let images = dict["images"] as? [[String: Any]] { return }
let imagesString: [String] =
for imageDict in images {
for key in imageDict.keys {
if let imageName = imageDict[key] as? String else {
// here you access your image as you want
imagesString.append(imageName)
}
}
}


Then when creating the post object you use imagesString that we created:



let newPost = Post(avatarString: avatar, contentString: content, imagesString: imagesString, nameString: name, timeDouble: time, typeString: type)





share|improve this answer















Add this to access your images:



guard let images = dict["images"] as? [[String: Any]] { return }
let imagesString: [String] =
for imageDict in images {
for key in imageDict.keys {
if let imageName = imageDict[key] as? String else {
// here you access your image as you want
imagesString.append(imageName)
}
}
}


Then when creating the post object you use imagesString that we created:



let newPost = Post(avatarString: avatar, contentString: content, imagesString: imagesString, nameString: name, timeDouble: time, typeString: type)






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 12 '18 at 14:55

























answered Nov 12 '18 at 9:52









DionizBDionizB

1,0452514




1,0452514













  • it doesn't work, show the error "Cannot subscript a value of type '[String : String]' with an index of type 'Dictionary<String, String>.Keys'"

    – Trung Nguyen
    Nov 12 '18 at 14:13











  • I fixed the error, check the edited answer

    – DionizB
    Nov 12 '18 at 14:46











  • i want to append it to array model Post. So how can i do that. The image already showed in collection view but it duplicate. How can i fix that

    – Trung Nguyen
    Nov 12 '18 at 14:52











  • I edited the answer again

    – DionizB
    Nov 12 '18 at 14:56











  • still doesn't work, please help me

    – Trung Nguyen
    Nov 12 '18 at 15:10



















  • it doesn't work, show the error "Cannot subscript a value of type '[String : String]' with an index of type 'Dictionary<String, String>.Keys'"

    – Trung Nguyen
    Nov 12 '18 at 14:13











  • I fixed the error, check the edited answer

    – DionizB
    Nov 12 '18 at 14:46











  • i want to append it to array model Post. So how can i do that. The image already showed in collection view but it duplicate. How can i fix that

    – Trung Nguyen
    Nov 12 '18 at 14:52











  • I edited the answer again

    – DionizB
    Nov 12 '18 at 14:56











  • still doesn't work, please help me

    – Trung Nguyen
    Nov 12 '18 at 15:10

















it doesn't work, show the error "Cannot subscript a value of type '[String : String]' with an index of type 'Dictionary<String, String>.Keys'"

– Trung Nguyen
Nov 12 '18 at 14:13





it doesn't work, show the error "Cannot subscript a value of type '[String : String]' with an index of type 'Dictionary<String, String>.Keys'"

– Trung Nguyen
Nov 12 '18 at 14:13













I fixed the error, check the edited answer

– DionizB
Nov 12 '18 at 14:46





I fixed the error, check the edited answer

– DionizB
Nov 12 '18 at 14:46













i want to append it to array model Post. So how can i do that. The image already showed in collection view but it duplicate. How can i fix that

– Trung Nguyen
Nov 12 '18 at 14:52





i want to append it to array model Post. So how can i do that. The image already showed in collection view but it duplicate. How can i fix that

– Trung Nguyen
Nov 12 '18 at 14:52













I edited the answer again

– DionizB
Nov 12 '18 at 14:56





I edited the answer again

– DionizB
Nov 12 '18 at 14:56













still doesn't work, please help me

– Trung Nguyen
Nov 12 '18 at 15:10





still doesn't work, please help me

– Trung Nguyen
Nov 12 '18 at 15:10











0














You can fetch the images values using this



ref.child("Posts").observe(.childAdded) { (snapshot) in

self.ref.child("Posts").child(snapshot.key).observe(.childAdded, with: { (snapshot1) in
self.ref.child("Posts").child(snapshot.key).child(snapshot1.key).child("images").observe(.childAdded, with: { (snap) in
let post = new Post()
for rest in snap.children.allObjects as! [DataSnapshot] {
//append images
post.imagesString.append(rest.value)
}


post.avatarString = snapshot1.value["avatar"] as? String
...
})
})


I suggest you change the structure of your db because its nested. Refer here






share|improve this answer


























  • how can i fetch image into Post array, and show it to collectionView. Please help me

    – Trung Nguyen
    Nov 12 '18 at 14:26













  • I edited the code. Try if it will work

    – elbert rivas
    Nov 12 '18 at 15:41













  • i will try it now. Thanks bro for your helping

    – Trung Nguyen
    Nov 13 '18 at 1:43











  • images from all post append in array images so each post show all of images from other post. please help me how to fix this

    – Trung Nguyen
    Nov 13 '18 at 1:56











  • Check my new answer @TrungNguyen

    – elbert rivas
    Nov 13 '18 at 3:15
















0














You can fetch the images values using this



ref.child("Posts").observe(.childAdded) { (snapshot) in

self.ref.child("Posts").child(snapshot.key).observe(.childAdded, with: { (snapshot1) in
self.ref.child("Posts").child(snapshot.key).child(snapshot1.key).child("images").observe(.childAdded, with: { (snap) in
let post = new Post()
for rest in snap.children.allObjects as! [DataSnapshot] {
//append images
post.imagesString.append(rest.value)
}


post.avatarString = snapshot1.value["avatar"] as? String
...
})
})


I suggest you change the structure of your db because its nested. Refer here






share|improve this answer


























  • how can i fetch image into Post array, and show it to collectionView. Please help me

    – Trung Nguyen
    Nov 12 '18 at 14:26













  • I edited the code. Try if it will work

    – elbert rivas
    Nov 12 '18 at 15:41













  • i will try it now. Thanks bro for your helping

    – Trung Nguyen
    Nov 13 '18 at 1:43











  • images from all post append in array images so each post show all of images from other post. please help me how to fix this

    – Trung Nguyen
    Nov 13 '18 at 1:56











  • Check my new answer @TrungNguyen

    – elbert rivas
    Nov 13 '18 at 3:15














0












0








0







You can fetch the images values using this



ref.child("Posts").observe(.childAdded) { (snapshot) in

self.ref.child("Posts").child(snapshot.key).observe(.childAdded, with: { (snapshot1) in
self.ref.child("Posts").child(snapshot.key).child(snapshot1.key).child("images").observe(.childAdded, with: { (snap) in
let post = new Post()
for rest in snap.children.allObjects as! [DataSnapshot] {
//append images
post.imagesString.append(rest.value)
}


post.avatarString = snapshot1.value["avatar"] as? String
...
})
})


I suggest you change the structure of your db because its nested. Refer here






share|improve this answer















You can fetch the images values using this



ref.child("Posts").observe(.childAdded) { (snapshot) in

self.ref.child("Posts").child(snapshot.key).observe(.childAdded, with: { (snapshot1) in
self.ref.child("Posts").child(snapshot.key).child(snapshot1.key).child("images").observe(.childAdded, with: { (snap) in
let post = new Post()
for rest in snap.children.allObjects as! [DataSnapshot] {
//append images
post.imagesString.append(rest.value)
}


post.avatarString = snapshot1.value["avatar"] as? String
...
})
})


I suggest you change the structure of your db because its nested. Refer here







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 12 '18 at 15:03

























answered Nov 12 '18 at 9:49









elbert rivaselbert rivas

332210




332210













  • how can i fetch image into Post array, and show it to collectionView. Please help me

    – Trung Nguyen
    Nov 12 '18 at 14:26













  • I edited the code. Try if it will work

    – elbert rivas
    Nov 12 '18 at 15:41













  • i will try it now. Thanks bro for your helping

    – Trung Nguyen
    Nov 13 '18 at 1:43











  • images from all post append in array images so each post show all of images from other post. please help me how to fix this

    – Trung Nguyen
    Nov 13 '18 at 1:56











  • Check my new answer @TrungNguyen

    – elbert rivas
    Nov 13 '18 at 3:15



















  • how can i fetch image into Post array, and show it to collectionView. Please help me

    – Trung Nguyen
    Nov 12 '18 at 14:26













  • I edited the code. Try if it will work

    – elbert rivas
    Nov 12 '18 at 15:41













  • i will try it now. Thanks bro for your helping

    – Trung Nguyen
    Nov 13 '18 at 1:43











  • images from all post append in array images so each post show all of images from other post. please help me how to fix this

    – Trung Nguyen
    Nov 13 '18 at 1:56











  • Check my new answer @TrungNguyen

    – elbert rivas
    Nov 13 '18 at 3:15

















how can i fetch image into Post array, and show it to collectionView. Please help me

– Trung Nguyen
Nov 12 '18 at 14:26







how can i fetch image into Post array, and show it to collectionView. Please help me

– Trung Nguyen
Nov 12 '18 at 14:26















I edited the code. Try if it will work

– elbert rivas
Nov 12 '18 at 15:41







I edited the code. Try if it will work

– elbert rivas
Nov 12 '18 at 15:41















i will try it now. Thanks bro for your helping

– Trung Nguyen
Nov 13 '18 at 1:43





i will try it now. Thanks bro for your helping

– Trung Nguyen
Nov 13 '18 at 1:43













images from all post append in array images so each post show all of images from other post. please help me how to fix this

– Trung Nguyen
Nov 13 '18 at 1:56





images from all post append in array images so each post show all of images from other post. please help me how to fix this

– Trung Nguyen
Nov 13 '18 at 1:56













Check my new answer @TrungNguyen

– elbert rivas
Nov 13 '18 at 3:15





Check my new answer @TrungNguyen

– elbert rivas
Nov 13 '18 at 3:15


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53258349%2ffetch-data-from-multiple-node-in-firebase-in-swift%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Florida Star v. B. J. F.

Error while running script in elastic search , gateway timeout

Adding quotations to stringified JSON object values