0

Возможно правильный совершенно другой подход(например сделать задержку перед запросом к серверу). Но используя такой способ видно, как последовательно выводится результат для каждой введённой буквы в SearchBar.

Вот код:

class MainTableViewController: UITableViewController {

    //UISearchController
    private var searchController = UISearchController(searchResultsController: nil)
    
    //responceData
    private var respData: RequestGithubData?
    private var filredArray = [RequestGithubData.Items]()
        
    
  
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Регистрация ячейки
        tableView.register(UINib(nibName: "MyTableViewMainCell", bundle: nil), forCellReuseIdentifier: "tVMainCell")
        searchController.automaticallyShowsSearchResultsController = true
        searchController.searchBar.isSearchResultsButtonSelected = true
        //Настройки navigation Bar
        navigationItem.title = "Finder github rep"
        navigationController?.navigationBar.prefersLargeTitles = true
        
        //setup the searchController
        searchController.searchResultsUpdater = self //Получатель информации об изменинии в строке поиска данный класс
        searchController.obscuresBackgroundDuringPresentation = false // Что бы не затемнялся отображаемый при поиске контент
        searchController.searchBar.placeholder = "Enter the Gir Repository name"
        
        navigationItem.searchController = searchController //Интеграция searchController в navigationBar
        definesPresentationContext = true // Опускает строку поиска при переходе на другой экран
    }
    
 
    override func numberOfSections(in tableView: UITableView) -> Int {
       
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        respData?.items?.count ?? 0
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tVMainCell", for: indexPath) as! MyTableViewMainCell//Для переиспользования ячеек( эффективное использование памяти)

        // Configure the cell...
        
       // cell.textLabel?.text = respData?.items?[indexPath.row].name
        cell.topLable.text = respData?.items?[indexPath.row].name
        cell.BottomLable.text = respData?.items?[indexPath.row].description
        
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        
       
    }
    


extension MainTableViewController: UISearchResultsUpdating {
    
    
    
    func updateSearchResults(for searchController: UISearchController) {
        
        guard let searchText = searchController.searchBar.text else { return }
        guard searchText != "" else { return }

        let foundStr = "https://api.github.com/search/repositories?q=" + searchText.lowercased()
        foundGithubRep(to: foundStr)
    }
    
    func foundGithubRep(to path: String) {
        guard let url = URL(string: path)
            else { return }
        
        URLSession.shared.dataTask(with: url) { (data, responce, error) in

            
            guard let data = data else { return }
            
            do {
                let decoder = JSONDecoder()
                decoder.dateDecodingStrategy = .iso8601
                self.respData = try decoder.decode(RequestGithubData.self, from: data)
            } catch {
                print( error )
            }
            
            // Отправляем вызов данного блока кода в основной поток
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
            
        }.resume()
    }
}
1
  • Если вам дан исчерпывающий ответ, отметьте его как принятый нажав на галочку слева от него.
    – Andrew
    31 окт 2020 в 8:33

1 ответ 1

1

Можно сделать URLSession.shared.dataTask... глобальной переменной и дальше проверять работает ли она или нет:

let task = URLSessionDataTask()

и дальше проверять:

if task.state != URLSession.state.running {
    // ничего не вызывается
} else {
    // обращение к апи идет
   task.cancel() // останавливаем запрос
   // шлем новый
}

так же можно остановить вызовы таким способом:

session.invalidateAndCancel()

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.