user23492857
user23492857

Reputation: 1

calling api with searchbar text in swiftui

I have a search bar, and the text in the searchbar indicates that API is calling. Even after removing everything from the search field, the user interface is still displaying the data. I have used DispatchWorkItem to cancle the task. Can anyone help me to fix the issue. Will it be helpful to use debounce technique here?

  private var searchWorkItem: DispatchWorkItem?

    func updateSearchResults(for searchController: UISearchController) {
        searchText = searchController.searchBar.text

        guard let query = searchText, lastSearch != query else {
            return
        }
            if query.count < 1 {
                lastSearch = ""
                performSearch1()
            } else {
                Task {
                    performSearch2(with: query)
                }
            }
    }
    private func performSearch2(with query: String) {
        searchWorkItem?.cancel()
        
        let task = DispatchWorkItem { [weak self] in
            guard let self = self else { return }
            Task {
                await self.search(query: query)
            }
        }
        
        searchWorkItem = task
        
        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500), execute: task)
        
      }
    private func performSearch1() {
        searchWorkItem?.cancel()
        
        let task = DispatchWorkItem { [weak self] in
            guard let self = self else { return }
            updateSections(
                using: .empty,
                query: ""
            )
        }
        
        searchWorkItem = task
        
        // Excute the workitem after 0.3 seconds.
        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500), execute: task)
            
        }
func search(query: String) async {
        lastSearch = query

        do {
            async let progressIDs = vodProgressStorage?.fetchProgresses() ?? [:]
            let model = try await searchRepository.search(
                text: query,
                context: (featureFlags, progressIDs)
            )
            await MainActor.run {
                self.updateSections(using: model, query: query)
            }
        } catch {
            os_log(.debug, Constants.Log.vodProductFetchError, "\(error)")
            analytics.log(.error(.search, error.localizedDescription))
            await MainActor.run {
                self.router.route(to: ErrorAlertRoute(error, retriableViewModel: self))
            }
        }
    }

Upvotes: 0

Views: 24

Answers (0)

Related Questions