I am having issues getting data from firebase database and adding them to array. The print output from the method getNewQuote shows that the array is empty but the screenshot shows that the label was updated within the getNewQuote method.
How can this be happening? Is there a latency on the event in the getNewQuote method that is causing this? moreover, how is it that the label was updated with the 4th iteration of the getNewQuote method and not the last iteration.
Thank you in advance!
Breakdown of Code
Iterate in loop 5 times and do the following:
1.create a random number
2. pass random number into the method getNewQuote
(This method gets back the data from the database and appends into the array quotesMessages)
After the iteration of the loop, the complete array is printed
Code:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var message: UILabel!
var QuoteRef:String = "https://motivatr.firebaseIO.com/quotes"
var quotesMessages = [String]()
/* */
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for (var i = 0; i < 5; i++) {
var currRandomNumber = self.createRandomNum()
self.getNewQuote(currRandomNumber)
}
println("viewDidLoad, array has \(quotesMessages.description)")
}//eom
/* */
override func viewWillAppear(animated: Bool) {
println("viewWillAppear, array has \(quotesMessages.description)")
}
/* */
override func viewDidAppear(animated: Bool) {
println("viewDidAppear, array has \(quotesMessages.description)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/* creates a random number */
func createRandomNum()-> Int {
var randomNumberRange = UInt32(49)
var UnsignedRandomNum = arc4random_uniform(randomNumberRange)
var randomNum = Int(UnsignedRandomNum)
return randomNum
}
/* gets a new data from databases */
func getNewQuote(randomNum: Int){
println("random number \(randomNum) created")
//Temp var's
var quoteText = ""
var quoteAuthor = ""
var DBQuoteURL = "\(QuoteRef)/\(randomNum)"
var myRootRef = Firebase(url:DBQuoteURL)
myRootRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if snapshot.value is NSNull {
// The value is null
}
else
{
if let quote = snapshot.value["quote"] as? String {
// println(quote)
quoteText = "'\(quote)'"
self.message.text = quoteText
self.quotesMessages.append(quoteText)
}
}
})
println("quote is: \(quoteText)")
}//eom
}//eoc
Output from console:
random number 24 created
quote is:
random number 18 created
quote is:
random number 45 created
quote is:
random number 47 created
quote is:
random number 34 created
quote is:
viewDidLoad, array has []
viewWillAppear, array has []
viewDidAppear, array has []
