Reputation: 63
I'm new to swift and using firebase, I'm making a simple application that let's user input a cellular prefix number and displays what cellular network is that number.
I'M having a hard problems with the if-else part. Whenever I add the else part, the label always displays "Missing" but whenever I print the snapshot.key and snapshot.value, I get the correct result in the console. When I remove the else part, it works. I'm really having a hard time figuring out the answer. Thanks in advance! Here is the code:
import UIKit
import Firebase
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
let loginButton: FBSDKLoginButton = {
let button = FBSDKLoginButton()
button.readPermissions = ["email"]
return button
}()
@IBOutlet weak var numField: UITextField!
@IBOutlet weak var answerField: UILabel!
@IBAction func enterButton(sender: AnyObject) {
matchNumber()
}
func matchNumber(){
let number: String = numField.text!
let numRef = Firebase(url: "https://npi2.firebaseio.com/num_details")
numRef.queryOrderedByKey().observeEventType(.ChildAdded, withBlock: { snapshot in
let network = snapshot.value as! String!
if snapshot.key == self.numField.text! {
self.answerField.text = network
}
else {
self.answerField.text = "Missing"
}
})
}
Upvotes: 0
Views: 118
Reputation: 4461
I think I know what is happening.
EXPLANATION:
1) You make your request to Firebase.
2) The request is asynch, so the code keeps running.
3) The request is not done yet, therefore the else
statement is executed because the value is not yet returned (checks for initial state).
4) When you remove the else
, the code executes the if
because there is nothing else to execute until the request is done (initial state is checked but there is no code to execute for it, then Firebase checks again because there is a data change and the if
statement is executed).
REFERENCE:
From the FIREBASE DOCUMENTATION (that you should have read before coming here :P)
"Firebase data is retrieved by attaching an asynchronous listener to a database reference. The listener will be triggered once for the initial state of the data and again anytime the data changes. This document will cover the basics of retrieving data, how data is ordered, and how to perform simple queries on data in your Firebase database."
https://www.firebase.com/docs/ios/guide/retrieving-data.html
SOLUTION:
Use the completion handler. It's made for that. Don't use else
statements inside your request like that. That's not how you use Firebase.
Upvotes: 1