So I am trying simply to whenever the user presses the return on key on a UITextField, the keyboard gets hidden, and THEN it calls a function. Right now I have:
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if(textField == _currentPasswordField)
{
[textField resignFirstResponder];
[_passwordField becomeFirstResponder];
return YES;
}
else if (textField == _passwordField)
{
[textField resignFirstResponder];
[_confirmPasswordField becomeFirstResponder];
return YES;
}
else
{
[textField resignFirstResponder];
[self changePassword];
return YES;
}
}
But the keyboard gets hidden after the entire changePassword function has returned. How can I hide it and THEN call my function?!
Thanks!
The problem is that your
changePasswordmethod takes a long time to run, because it’s talking to a server over the network.All user interface updates, such as the keyboard hiding animation, are triggered from the main thread. When you call a slow method on the main thread, you prevent those user interface updates from happening.
You need to move the call to
changePasswordoff the main thread. There are many ways to do this. One of the simplest ways is to use Grand Central Dispatch (GCD), like this:However, this is not safe unless your
changePasswordmethod is thread-safe, so you need to think about what you’re doing inchangePasswordand what will happen it it’s running on a background thread while other methods are running on the main thread.You need to read the Concurrency Programming Guide, or watch some of the WWDC videos, like Session 211 – Simplifying iPhone App Development with Grand Central Dispatch from WWDC 2010.