S
S
Shakedown2022-01-27 17:31:01
iOS
Shakedown, 2022-01-27 17:31:01

Swift, why does the UI freeze?

I am making an application for downloading photos. I go to the search, write a query, the loading animation starts, and the UI becomes unresponsive. Everything returns to normal after loading the pictures.
All UI updates happen on the main thread, other calculations happen on other threads

. This is the API manager:

func loadImages(searchingImage: String, page: Int, completion: @escaping (SearchCodable?, Error?) -> Void) {

        DispatchQueue.global(qos: .background).async {
            let session = URLSession(configuration: self.configuration)
            let urlString = self.baseUrl + self.pixabayApiKey + "&q=\(searchingImage)" + "&page=\(page)" + "&per_page=9"
            guard let imageURL = URL(string: urlString) else {
                completion(nil, nil)

                return
            }

            var request = URLRequest(url: imageURL)
            request.cachePolicy = .reloadIgnoringLocalCacheData
            request.httpMethod = "GET"

            let dataTask = session.dataTask(with: request) { data, response, error in
                if let data = data {
                    let searchingCodable = try? JSONDecoder().decode(SearchCodable.self, from: data)
                    completion(searchingCodable, error)
                } else {
                    completion(nil, error)
                }
            }

            dataTask.resume()
        }
    }


This is the method that the manager encapsulates:
private func loadImages() {
        let spinner = createSpinnerFooter()
        
        DispatchQueue.main.async {
            self.view.addSubview(spinner)
        }
        
        networkService.loadImages(searchingImage: searchingImage!, page: page) { [weak self] response, error in
            if let response = response {
                
                for hit in response.hits {
                    let wallpaperImage: WallpaperImage = (self?.converter.convertToImage(hit: hit))!
                    self?.images.append(wallpaperImage)
                }
                
                DispatchQueue.main.async {
                    self?.collectionView.reloadData()
                    spinner.removeFromSuperview()
                }
                
                self?.isLoading = false
            } else {
                print(error as Any)
            }
        }
    }


The following is a call to this method:
@objc private func didTapSearch() {
        guard let searchingText: String = searchingTextField.text?.trimmingCharacters(in: .whitespaces) else { return }
        
        images = []
        searchingImage = searchingText
        loadImages()
        searchingTextField.resignFirstResponder()
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question