How to trigger a function after certain time once typing ends in Swift?

How to trigger a function after certain time once typing ends in Swift?

Hello everyone! Today I am going to show you how you can trigger a method after certain duration which executes only after you stop typing. Well, you might think there is a delegate method provided by UITextFieldDelegate as func textFieldDidEndEditing(_ textField: UITextField). But this method executes only after the keyboard is dismissed. So, what if we want to execute a method after certain time while the typing is stopped? Well, let me tell you the secret. ?

While doing online search we normally use UISearchBar. But it is not good idea to send server request either using searchBarTextDidEndEditing nor textDidChange methods provided by UISearchBarDelegate. If didEndEditing is used, only after keyboard is dismissed, the request can be executed. And if textDidChange is used, each and every time after the key is pressed, a server request is made. Both approach is not good.


extension NSObject {
    func smSearch(text: String, action: Selector, afterDelay: Double = 0.5) {
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        perform(action, with: text, afterDelay: afterDelay)

Once you add this extension in your project, you can call this method from all class which inherits NSObject class. UIViewController is also one of them. So, you can use this function within your viewController class. Here is an example of how you can use it.

extension YourViewController: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        smSearch(text: searchText, action: #selector(delaySearch(with:)), afterDelay: 0.5)
    @objc func delaySearch(with: String) {

You can alter afterDelay value to whatever you want. Now after implementing this approach, once typing is done, only after 0.5 second, delaySearch(with:) method will be executed. Isn’t that cool. I hope so.

Well guys and girls, that’s all for today. I really hope, this is helpful to you. Let me know if there is any confusion. I will be happy to reply you back.


Tags :

Leave a Reply