Swift Array Empty After Appending in Loop












0















I am appending user info from Firebase into an array but it seems like the array(usersArray) is empty in all prints after the loop. The array is declared outside the function. Any ideas why? Thank you.



    func fetchAllUsers(completion: @escaping (_ message: String) -> Void){

//User or advertiser?
let uid = Auth.auth().currentUser?.uid

Database.database().reference(withPath: "Advertiser").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in

if snapshot.exists(){

myAdvertiserVar.advertiser = true

// Fetch all users
self.ref?.child("Users").observe(DataEventType.childAdded, with: { (snapshot) in


if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.nameLabel = dictionary["Username"] as? String
user.occupationLocation = dictionary["Occupation"] as? String
user.ageLabel = dictionary["Age"] as? String
user.infoText = dictionary["Bio"] as? String
user.emailText = dictionary["email"] as? String

let email = user.emailText
let ref = Database.database().reference().child("Users")
ref.queryOrdered(byChild: "email").queryEqual(toValue: email).observeSingleEvent(of: .childAdded, with: { (snapshot) in
user.toId = snapshot.key

})

self.usersArray.append(user)

}
})
dump(self.usersArray) //This print is empty
completion("FetchAllUsers")

}
}









share|improve this question

























  • stackoverflow.com/a/44490781/5009432. Reference this -- your difference and this is that you need to add the completion INSIDE your observe function, whereas it will know when it is done. Yours does not.

    – impression7vx
    Nov 15 '18 at 19:00













  • This did not solve it for me, It only produces prints until the looping has ended. Not only one single print and one completion message as i wish for. Do you know why?

    – olle
    Nov 15 '18 at 19:28











  • Yea, one sec. Gonna add answer.

    – impression7vx
    Nov 15 '18 at 19:31











  • stackoverflow.com/a/42615219/5009432. Here, this shows you how to determine when Firebase is done calling. You can't do it your way as you are . observing through each child, and you never know which 1 is the last.

    – impression7vx
    Nov 15 '18 at 19:41






  • 1





    You are missing the concept of "asynchronism". If you add print("will append") just before self.usersArray.append(user), and print("will call completion") just before completion("FetchAllUsers") you'll see that the order of the output is not the one you think of...

    – Larme
    Nov 15 '18 at 19:48
















0















I am appending user info from Firebase into an array but it seems like the array(usersArray) is empty in all prints after the loop. The array is declared outside the function. Any ideas why? Thank you.



    func fetchAllUsers(completion: @escaping (_ message: String) -> Void){

//User or advertiser?
let uid = Auth.auth().currentUser?.uid

Database.database().reference(withPath: "Advertiser").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in

if snapshot.exists(){

myAdvertiserVar.advertiser = true

// Fetch all users
self.ref?.child("Users").observe(DataEventType.childAdded, with: { (snapshot) in


if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.nameLabel = dictionary["Username"] as? String
user.occupationLocation = dictionary["Occupation"] as? String
user.ageLabel = dictionary["Age"] as? String
user.infoText = dictionary["Bio"] as? String
user.emailText = dictionary["email"] as? String

let email = user.emailText
let ref = Database.database().reference().child("Users")
ref.queryOrdered(byChild: "email").queryEqual(toValue: email).observeSingleEvent(of: .childAdded, with: { (snapshot) in
user.toId = snapshot.key

})

self.usersArray.append(user)

}
})
dump(self.usersArray) //This print is empty
completion("FetchAllUsers")

}
}









share|improve this question

























  • stackoverflow.com/a/44490781/5009432. Reference this -- your difference and this is that you need to add the completion INSIDE your observe function, whereas it will know when it is done. Yours does not.

    – impression7vx
    Nov 15 '18 at 19:00













  • This did not solve it for me, It only produces prints until the looping has ended. Not only one single print and one completion message as i wish for. Do you know why?

    – olle
    Nov 15 '18 at 19:28











  • Yea, one sec. Gonna add answer.

    – impression7vx
    Nov 15 '18 at 19:31











  • stackoverflow.com/a/42615219/5009432. Here, this shows you how to determine when Firebase is done calling. You can't do it your way as you are . observing through each child, and you never know which 1 is the last.

    – impression7vx
    Nov 15 '18 at 19:41






  • 1





    You are missing the concept of "asynchronism". If you add print("will append") just before self.usersArray.append(user), and print("will call completion") just before completion("FetchAllUsers") you'll see that the order of the output is not the one you think of...

    – Larme
    Nov 15 '18 at 19:48














0












0








0








I am appending user info from Firebase into an array but it seems like the array(usersArray) is empty in all prints after the loop. The array is declared outside the function. Any ideas why? Thank you.



    func fetchAllUsers(completion: @escaping (_ message: String) -> Void){

//User or advertiser?
let uid = Auth.auth().currentUser?.uid

Database.database().reference(withPath: "Advertiser").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in

if snapshot.exists(){

myAdvertiserVar.advertiser = true

// Fetch all users
self.ref?.child("Users").observe(DataEventType.childAdded, with: { (snapshot) in


if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.nameLabel = dictionary["Username"] as? String
user.occupationLocation = dictionary["Occupation"] as? String
user.ageLabel = dictionary["Age"] as? String
user.infoText = dictionary["Bio"] as? String
user.emailText = dictionary["email"] as? String

let email = user.emailText
let ref = Database.database().reference().child("Users")
ref.queryOrdered(byChild: "email").queryEqual(toValue: email).observeSingleEvent(of: .childAdded, with: { (snapshot) in
user.toId = snapshot.key

})

self.usersArray.append(user)

}
})
dump(self.usersArray) //This print is empty
completion("FetchAllUsers")

}
}









share|improve this question
















I am appending user info from Firebase into an array but it seems like the array(usersArray) is empty in all prints after the loop. The array is declared outside the function. Any ideas why? Thank you.



    func fetchAllUsers(completion: @escaping (_ message: String) -> Void){

//User or advertiser?
let uid = Auth.auth().currentUser?.uid

Database.database().reference(withPath: "Advertiser").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in

if snapshot.exists(){

myAdvertiserVar.advertiser = true

// Fetch all users
self.ref?.child("Users").observe(DataEventType.childAdded, with: { (snapshot) in


if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.nameLabel = dictionary["Username"] as? String
user.occupationLocation = dictionary["Occupation"] as? String
user.ageLabel = dictionary["Age"] as? String
user.infoText = dictionary["Bio"] as? String
user.emailText = dictionary["email"] as? String

let email = user.emailText
let ref = Database.database().reference().child("Users")
ref.queryOrdered(byChild: "email").queryEqual(toValue: email).observeSingleEvent(of: .childAdded, with: { (snapshot) in
user.toId = snapshot.key

})

self.usersArray.append(user)

}
})
dump(self.usersArray) //This print is empty
completion("FetchAllUsers")

}
}






arrays swift firebase firebase-realtime-database






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 5:34









PradyumanDixit

2,1872820




2,1872820










asked Nov 15 '18 at 18:43









olleolle

4929




4929













  • stackoverflow.com/a/44490781/5009432. Reference this -- your difference and this is that you need to add the completion INSIDE your observe function, whereas it will know when it is done. Yours does not.

    – impression7vx
    Nov 15 '18 at 19:00













  • This did not solve it for me, It only produces prints until the looping has ended. Not only one single print and one completion message as i wish for. Do you know why?

    – olle
    Nov 15 '18 at 19:28











  • Yea, one sec. Gonna add answer.

    – impression7vx
    Nov 15 '18 at 19:31











  • stackoverflow.com/a/42615219/5009432. Here, this shows you how to determine when Firebase is done calling. You can't do it your way as you are . observing through each child, and you never know which 1 is the last.

    – impression7vx
    Nov 15 '18 at 19:41






  • 1





    You are missing the concept of "asynchronism". If you add print("will append") just before self.usersArray.append(user), and print("will call completion") just before completion("FetchAllUsers") you'll see that the order of the output is not the one you think of...

    – Larme
    Nov 15 '18 at 19:48



















  • stackoverflow.com/a/44490781/5009432. Reference this -- your difference and this is that you need to add the completion INSIDE your observe function, whereas it will know when it is done. Yours does not.

    – impression7vx
    Nov 15 '18 at 19:00













  • This did not solve it for me, It only produces prints until the looping has ended. Not only one single print and one completion message as i wish for. Do you know why?

    – olle
    Nov 15 '18 at 19:28











  • Yea, one sec. Gonna add answer.

    – impression7vx
    Nov 15 '18 at 19:31











  • stackoverflow.com/a/42615219/5009432. Here, this shows you how to determine when Firebase is done calling. You can't do it your way as you are . observing through each child, and you never know which 1 is the last.

    – impression7vx
    Nov 15 '18 at 19:41






  • 1





    You are missing the concept of "asynchronism". If you add print("will append") just before self.usersArray.append(user), and print("will call completion") just before completion("FetchAllUsers") you'll see that the order of the output is not the one you think of...

    – Larme
    Nov 15 '18 at 19:48

















stackoverflow.com/a/44490781/5009432. Reference this -- your difference and this is that you need to add the completion INSIDE your observe function, whereas it will know when it is done. Yours does not.

– impression7vx
Nov 15 '18 at 19:00







stackoverflow.com/a/44490781/5009432. Reference this -- your difference and this is that you need to add the completion INSIDE your observe function, whereas it will know when it is done. Yours does not.

– impression7vx
Nov 15 '18 at 19:00















This did not solve it for me, It only produces prints until the looping has ended. Not only one single print and one completion message as i wish for. Do you know why?

– olle
Nov 15 '18 at 19:28





This did not solve it for me, It only produces prints until the looping has ended. Not only one single print and one completion message as i wish for. Do you know why?

– olle
Nov 15 '18 at 19:28













Yea, one sec. Gonna add answer.

– impression7vx
Nov 15 '18 at 19:31





Yea, one sec. Gonna add answer.

– impression7vx
Nov 15 '18 at 19:31













stackoverflow.com/a/42615219/5009432. Here, this shows you how to determine when Firebase is done calling. You can't do it your way as you are . observing through each child, and you never know which 1 is the last.

– impression7vx
Nov 15 '18 at 19:41





stackoverflow.com/a/42615219/5009432. Here, this shows you how to determine when Firebase is done calling. You can't do it your way as you are . observing through each child, and you never know which 1 is the last.

– impression7vx
Nov 15 '18 at 19:41




1




1





You are missing the concept of "asynchronism". If you add print("will append") just before self.usersArray.append(user), and print("will call completion") just before completion("FetchAllUsers") you'll see that the order of the output is not the one you think of...

– Larme
Nov 15 '18 at 19:48





You are missing the concept of "asynchronism". If you add print("will append") just before self.usersArray.append(user), and print("will call completion") just before completion("FetchAllUsers") you'll see that the order of the output is not the one you think of...

– Larme
Nov 15 '18 at 19:48












0






active

oldest

votes











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%2f53326017%2fswift-array-empty-after-appending-in-loop%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















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%2f53326017%2fswift-array-empty-after-appending-in-loop%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

Bressuire

Vorschmack

Quarantine