From 6c7af886b41c4a152e9fb5930e79a4c27e1266ce Mon Sep 17 00:00:00 2001
From: lazarog98 <lazarog98@87-77-95-50.mna.fu-berlin.de>
Date: Tue, 25 Feb 2020 16:03:06 +0100
Subject: [PATCH] Add delay when searching

---
 enzevalos_iphone/InboxViewController.swift | 20 +++++++++++++++++---
 1 file changed, 17 insertions(+), 3 deletions(-)

diff --git a/enzevalos_iphone/InboxViewController.swift b/enzevalos_iphone/InboxViewController.swift
index 42b4d199..c9693df3 100644
--- a/enzevalos_iphone/InboxViewController.swift
+++ b/enzevalos_iphone/InboxViewController.swift
@@ -39,6 +39,7 @@ class InboxViewController: UITableViewController, InboxCellDelegator {
             }
         }
     }
+    var searchBarTimer: Timer?
 
     @IBOutlet weak var lastUpdateButton: UIBarButtonItem!
     var lastUpdateLabel = UILabel(frame: CGRect.zero)
@@ -248,7 +249,20 @@ class InboxViewController: UITableViewController, InboxCellDelegator {
         return searchController.isActive && !searchBarIsEmpty
     }
 
-    func filterContentForSearchText(_ searchText: String, scope: Int = 0) {
+    /// searches a given string with a delay so that the entire client doesn't lag if the inbox is very big
+    func startSearch(searchText: String, scope: Int = 0) {
+        if #available(iOS 10.0, *) {
+            if let searchBarTimer: Timer = self.searchBarTimer {
+                searchBarTimer.invalidate()
+            }
+            
+            self.searchBarTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false, block: { _ in
+                self.filterContentForSearchText(searchText, scope: scope)
+            })
+        }
+    }
+    
+    private func filterContentForSearchText(_ searchText: String, scope: Int = 0) {
         var records = [KeyRecord]()
         if scope == 0 || scope == 3 {
             records += folder.records.filter({ (record: KeyRecord) -> Bool in
@@ -286,13 +300,13 @@ extension InboxViewController: UISearchResultsUpdating {
     // https://www.raywenderlich.com/157864/uisearchcontroller-tutorial-getting-started
 
     func updateSearchResults(for searchController: UISearchController) {
-        filterContentForSearchText(searchController.searchBar.text!, scope: searchController.searchBar.selectedScopeButtonIndex)
+        startSearch(searchText: searchController.searchBar.text!, scope: searchController.searchBar.selectedScopeButtonIndex)
     }
 }
 
 extension InboxViewController: UISearchBarDelegate {
     func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
-        filterContentForSearchText(searchBar.text!, scope: selectedScope)
+        startSearch(searchText: searchBar.text!, scope: selectedScope)
     }
 }
 
-- 
GitLab