Swift tableView slow and scrollable lag

I am fetching data from json API. The table view call fills up, but very slow and lags when scrolling down, as the table loads faster. I am new to swift and xcode, any advice would be appreciated

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 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
}

}

      

+3


source to share


2 answers


NSData(contentsOf: (imgURL as URL?)!)

is synchronous. Please refer to the SDK doc: https://developer.apple.com/reference/foundation/nsdata/1547245-datawithcontentsofurl
Which state:



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.

      

+8


source


You can use this module to speed up https://github.com/rs/SDWebImage It will be convenient to upload images.



+1


source







All Articles