I'm making a social media app and one of the features in the sign up screen is it checks if the username is taken in real time and puts an X or Check if it's taken (again in real time). I use a timer to accomplish this but for some reason the timer stops after a few seconds. What's going on? And is there a better way of going about doing this?
override func viewDidLoad() {
username.delegate = self
email.delegate = self
password.delegate = self
var timer = NSTimer()
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("checkOrX"), userInfo: nil, repeats: true)
}
func checkOrX() {
var query = PFQuery(className: "_User")
query.whereKey("username", equalTo: self.username.text)
query.findObjectsInBackgroundWithBlock { (users, error) -> Void in
if let users = users {
self.usernameCheck.image = UIImage(named: "X.png")
} else {
self.usernameCheck.image = UIImage(named: "Check.png")
}
}
}
Instead of sending 100 requests a second which is bad for multiple reasons, you should send a request at most every time the user changes the actual user name.
Why your current solution is bad:
What you could do:
An example version of the first "solution" would probably look like
func viewDidLoad() {
// ...
self.username.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
}
func textFieldDidChange(textField: UITextField) {
if textField == self.username {
checkOrX()
}
}