ios - 下载 JSON 时如何修复延迟的 UITableView 滚动性能?

标签 ios json swift multithreading uitableview

在我的应用程序中,我从互联网上下载了一个 JSON 文件,并用该文件中的项目填充了一个 UITableView。它确实运行良好,没有任何问题或错误,但滚动性能非常滞后,并且 UI 出现了一点点故障。

我认为这是因为我正在从 JSON 文件下载图像,所以我研究了多线程,但我认为我做的不对,因为它确实 加载速度更快,但滚动性能仍然和以前一样。

有人可以告诉我如何解决这个问题吗?这个 UITableView 是应用程序中最重要的东西,我花了很多时间试图修复它。谢谢!

这是我的代码-

import UIKit

class ViewController: UIViewController, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

var nameArray = [String]()
var idArray = [String]()
var ageArray = [String]()
var genderArray = [String]()
var descriptionArray = [String]()
var imgURLArray = [String]()

let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)

final let urlString = "https://pbsocfilestorage.000webhostapp.com/jsonDogs.json"

override func viewDidLoad() {
    super.viewDidLoad()

    self.downloadJsonWithURL()

    // Activity Indicator
    myActivityIndicator.center = view.center
    myActivityIndicator.hidesWhenStopped = true
    myActivityIndicator.startAnimating()
    view.addSubview(myActivityIndicator)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func downloadJsonWithURL() {
    let url = NSURL(string:urlString)
    URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
        Void in
        print("Good so far...")
        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
            print(jsonObj!.value(forKey: "dogs"))

            if let dogArray = jsonObj!.value(forKey: "dogs") as? NSArray {
                print("Why u no work!")
                for dog in dogArray {

                    if let dogDict = dog as? NSDictionary {
                        if let name = dogDict.value(forKey: "name") {
                            self.nameArray.append(name as! String)
                        }
                        if let name = dogDict.value(forKey: "id") {
                            self.idArray.append(name as! String)
                        }
                        if let name = dogDict.value(forKey: "age") {
                            self.ageArray.append(name as! String)
                        }
                        if let name = dogDict.value(forKey: "gender") {
                            self.genderArray.append(name as! String)
                        }
                        if let name = dogDict.value(forKey: "image") {
                                self.imgURLArray.append(name as! String)
                        }
                        if let name = dogDict.value(forKey: "description") {
                            self.descriptionArray.append(name as! String)
                        }

                        OperationQueue.main.addOperation ({
                            self.myActivityIndicator.stopAnimating()
                            self.tableView.reloadData()
                        })

                    }
                }
            }
        }

    }).resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return nameArray.count
}

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return  UITableViewAutomaticDimension;
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let imgURL = NSURL(string: imgURLArray[indexPath.row])
    let cell = tableView.dequeueReusableCell(withIdentifier: "reusableCell") as! TableViewCell

    URLSession.shared.dataTask(with: (imgURL as! URL), completionHandler: {(data, resp, error) -> Void in

        if (error == nil && data != nil) {
            OperationQueue.main.addOperation({
                cell.dogNameLabel.text = self.nameArray[indexPath.row]
                cell.idLabel.text = self.idArray[indexPath.row]
                cell.ageLabel.text = self.ageArray[indexPath.row]
                cell.genderLabel.text = self.genderArray[indexPath.row]
                print("Cell info was filled in!")

                if imgURL != nil {
                    let data = NSData(contentsOf: (imgURL as? URL)!)
                    cell.dogImage.image = UIImage(data: data as! Data)
                }
            })
        }
    }).resume()

    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDog" {
        if let indexPath = self.tableView.indexPathForSelectedRow{
            let detailViewController = segue.destination as! DetailViewController
            detailViewController.imageString = imgURLArray[indexPath.row]
            detailViewController.nameString = nameArray[indexPath.row]
            detailViewController.idString = idArray[indexPath.row]
            detailViewController.ageString = ageArray[indexPath.row]
            detailViewController.descriptionString = descriptionArray[indexPath.row]
            detailViewController.genderString = genderArray[indexPath.row]
        }
    }
}
}

最佳答案

这是一个很大的错误。您正在使用 dataTask 加载数据,但您根本没有使用返回的数据。而不是您使用同步 contentsOf 第二次加载数据。不要那样做。

并且不要更新异步完成 block 中的标签。字符串与图像数据无关。

这样效率更高:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let imgURL = URL(string: imgURLArray[indexPath.row])
    let cell = tableView.dequeueReusableCell(withIdentifier: "reusableCell", for: indexPath) as! TableViewCell

    cell.dogNameLabel.text = self.nameArray[indexPath.row]
    cell.idLabel.text = self.idArray[indexPath.row]
    cell.ageLabel.text = self.ageArray[indexPath.row]
    cell.genderLabel.text = self.genderArray[indexPath.row]
    print("Cell info was filled in!")

    URLSession.shared.dataTask(with: imgURL!) { (data, resp, error) in

        if let data = data {
            OperationQueue.main.addOperation({
                cell.dogImage.image = UIImage(data: data)
            })
        }
    }.resume()

    return cell
}

注意:强烈建议您不要使用多个数组作为数据源。这是非常容易出错的。使用自定义结构或类。并使用 URL 实例而不是字符串创建 imgURLArray。这也更有效率。

不过,您应该使用下载管理器来缓存图像并在单元格离开屏幕时取消下载。目前,当用户滚动时,每个图像都会再次下载,并且会针对该特定单元格再次调用 cellForRow

关于ios - 下载 JSON 时如何修复延迟的 UITableView 滚动性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43967440/

相关文章:

javascript - 通过匹配文本将 json 数据放入数组中

ios - didReceiveRemoteNotification 或 ReceivedRemoteNotification 从不触发

ios - Apple Mach - O 链接器错误。没有这样的文件或目录 Swifty Json

c# - 查看Json响应码,发现windows phone 8.1的错误

ios - Appcelerator - 如何在 iOS9 应用程序中添加通用链接支持

android json响应键值,解析

ios - 如何在iOS中运行相互依赖的长时间运行任务

ios - 如何重置 subview ?

ios - Xcode 6.3/iOS 8.3 中的新功能 : using self alloc for convenience constructor causes build error

ios - 使用 Swift 进行卡片查看