简体   繁体   中英

DispatchQueue.main.async causes the search to hang. Swift

I have a tableView, each cell is loaded with an image from the internet via DispatchQueue.main.async.

I implemented a search on an array, the data from which is output to a table. Because of DDispatchQueue.main.async, the emulator starts to hang a lot, but if you remove it, everything works fine, how do I implement loading images without causing a load?

Image upload code:

DispatchQueue.main.async {
       if let url = URL(string: "https://storage.googleapis.com/iex/api/logos/\(stock.displaySymbol).png") {
           if let data = try? Data(contentsOf: url) {
                self.stockLogoImageView.image = UIImage(data: data)
                self.imageLoadingIndicator.stopAnimating()
           } 
       }
}

Search extension code:

extension StocksViewController: UISearchResultsUpdating {
    func updateSearchResults(for searchController: UISearchController) {
        searchStocks(searchController.searchBar.text!)
    }
    
    func searchStocks(_ searchText: String) {
        searchStocksList = stocks.filter({(stock: Stock) -> Bool in
            return stock.displaySymbol.lowercased().contains(searchText.lowercased()) || stock.description.lowercased().contains(searchText.lowercased())
        })
        
        stocksTableView.reloadData()
        
    }
}

Don't do networking on the main queue, It's the UIKit work that must be done on the main queue.

   // Network on background queue
   if let url = URL(string: ....),
      let data = try? Data(contentsOf: url) {
        let img = UIImage(data: data)

        // Dispatch back to main to update UI
        DispatchQueue.main.async {
           self.stockLogoImageView.image = img
           self.imageLoadingIndicator.stopAnimating()
       }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM