табличное представление застревает во время нумерации страниц из-за сетевого запроса с использованием URLSession - PullRequest
0 голосов
/ 15 мая 2019

Я использовал Эта ссылка для вызова запроса API в моем коде.как показано ниже

        SpeedyNetworking.getUrl(url: url,isSetHeader: Constants.isTokenReqired) {[weak self] (response) in
        guard let strongSelf = self else {
            return
        }
        if response.success {

            if response.statusCode == 200{
               // var model : [FeedNewModel]?
                if let model = response.result(model: [FeedNewModel].self){
                    strongSelf.isDataLoading = false
                    if model.count > 0{
                        strongSelf.resCount = model.count
                        strongSelf.feedModel.append(contentsOf : model)
                        strongSelf.feedviewModel = strongSelf.feedModel.map({
                            return try! FeedNewViewModel(model: $0, Delegate: strongSelf.delegate)})
                    }
                    DispatchQueue.main.async {
                        //Reload with delay
                        strongSelf.stopActivityIndicator()
                        strongSelf.refreshControl.endRefreshing()
                        strongSelf.tableView.reloadData()
                    }
                }
            }else{
                strongSelf.showAlert(title: Constants.SERVER_ERROR, msg: Constants.EXECPTION)
                strongSelf.stopActivityIndicator()
            }
        }else{
            strongSelf.stopActivityIndicator()
        }
    }

Код работает нормально для самого первого запроса.Когда я пытаюсь разбить на страницы UITableView, пользовательский интерфейс застревает.Я использовал здесь архитектуру MVVM и прикрепил feedviewModel к UITableView.С этим в UITableView я также загружаю изображение с URL.Для этой цели я имею в виду следующий код

class ImageLoader: UIImageView {

var imageURL: URL?

let activityIndicator = UIActivityIndicatorView()

func loadImageWithUrl(_ url: URL) {

    // setup activityIndicator...
    activityIndicator.color = .darkGray

    addSubview(activityIndicator)
    activityIndicator.translatesAutoresizingMaskIntoConstraints = false
    activityIndicator.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    imageURL = url

    image = nil
   activityIndicator.startAnimating()

    // retrieves image if already available in cache
    if let imageFromCache = imageCache.object(forKey: url as AnyObject) as? UIImage {

        self.image = imageFromCache
        activityIndicator.stopAnimating()
        return
    }
    DispatchQueue.global(qos: .userInitiated).async {        // image does not available in cache.. so retrieving it from url...
    URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in

        if error != nil {
            print(error as Any)
            DispatchQueue.main.async(execute: {
            self.activityIndicator.stopAnimating()
            })
            return
        }
    //
        DispatchQueue.main.async(execute: {
            if let unwrappedData = data, let imageToCache = UIImage(data: unwrappedData) {

                if self.imageURL == url {
                    self.image = imageToCache
                }

                imageCache.setObject(imageToCache, forKey: url as AnyObject)
            }

            self.activityIndicator.stopAnimating()
        })
    }).resume()
    }
}
}

Код нумерации страниц приведен ниже

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    //scroll dragging
    spinner.stopAnimating()
    if ((tableView.contentOffset.y + tableView.frame.size.height) >= tableView.contentSize.height)
    {

        if !isDataLoading!{
            isDataLoading = true
            self.pageNo = self.pageNo + 1
            if self.resCount == Int(self.pagecount!){
                self.fetchdataNew(page: String(describing: self.pageNo))
            }else{
                let view = "No More Feeds"
                let label = UILabel()
                label.text = view
                label.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: tableView.bounds.width, height: CGFloat(44))
                label.textAlignment = .center
                self.tableView.tableFooterView = label
                self.tableView.tableFooterView?.isHidden = false
            }
        }

    }

}

Но пользовательский интерфейс застревает / останавливается, когда мы разбиваем на страницы UITableView.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...