Swift tableView缓慢且滚动滞后

瑞安·哈伯德(Ryan Hubbard)

我正在从json API中提取数据调用时会填充表格视图,但是向下滚动时会非常缓慢且滞后,如何加快表格的加载速度。我是Swift和Xcode的新手,不胜感激

import Foundation
import UIKit


class featuredViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {


@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!

// Array for JSON Data
var property: [featuredClass.property] = []
var imageArray = [String]()
var imageCollection = [[String]]()
var refreshControl: UIRefreshControl!


override func viewDidLoad() {
    super.viewDidLoad()
    self.getProperties()

    // Do any additional setup after loading the view, typically from a nib.
    refreshControl = UIRefreshControl()
    refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
    refreshControl.addTarget(self, action: #selector(featuredViewController.getProperties), for: UIControlEvents.valueChanged)
    tableView.addSubview(refreshControl)
}

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

let downloadTask = APICalls.getFeatured()

 URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in

    if let httpResponse = response as? HTTPURLResponse {
        print("statusCode: \(httpResponse.statusCode)")
    }

    /******** Parse JSON **********/
    do {       // A Dictionary of Dictionaries
        let jsonObject = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)

            if let jsonDict = jsonObject as? NSDictionary {
                // Do smthg.
                //print(jsonDict) // Debug the json

                let meCount = Int((jsonDict.count)) - 1; //get number to use for our loop


                    for index in 0...meCount {

                        for (_, value) in jsonDict { //Turns every key's value into a dictionary
                            // Fill property struct from json
                            self.property.append(featuredClass.property.init(jsonDict: value as! NSDictionary))
                            //print(self.property) // Uncomment for debugging


                            /**  Get Image 0 for featured Image **/
                                let myData = self.property[index].image
                               // print(myData ?? "Error")

                                if myData?["0"] != nil {
                                    let myData2 = myData?["0"] as! NSDictionary

                                    self.imageArray.append(myData2["url"] as! String)
                                    //print(myData2["url"] as! String)
                                }
                                else {
                                    self.imageArray.append("\(#imageLiteral(resourceName: "property-placeholder-800x500"))")
                                }
                            /* ENd Get image 0 */

                        }
                    }

            }

    }catch {
        //...
    }
    let meCount = (self.property.count)-1
    /******** End Parse JSON **********/
    //print(meCount)

    if meCount != -1 {
    }
    else {
        // Show alert view
        let contactAddedAlert = UIAlertController(title: "Error: Check if Access Key is correct",
                                                  message: nil, preferredStyle: .alert)
        contactAddedAlert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
        self.present(contactAddedAlert, animated: true, completion: nil)

    }
 /******** Reload table View **********/
 OperationQueue.main.addOperation({
 self.tableView.reloadData()
    self.refreshControl.endRefreshing()
 })        }).resume()
 }
/***********************************************************************************************/
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return property.count
}
/***********************************************************************************************/
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellFeatured") as! featuredTableViewCell
    cell.addressLabel.text = property[indexPath.row].address
    cell.cityNameLabel.text = property[indexPath.row].cityName

    let imgURL = NSURL(string: imageArray[indexPath.row])

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

    return cell
}

}
开玩笑的人

NSData(contentsOf: (imgURL as URL?)!)是同步的。请参阅SDK文档:https : //developer.apple.com/reference/foundation/nsdata/1547245-datawithcontentsofurl
其中指出:

Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.
Instead, for non-file URLs, consider using the dataTaskWithURL:completionHandler: method of the NSURLSession class. See URL Session Programming Guide for details.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章