2017-05-10 67 views
3

我從一個json API中提取數據調用表視圖填充,但是很慢並且在向下滾動時滯後我如何加速表的加載。我是新來的迅速和Xcode的任何提示將是讚賞Swift tableView緩慢滾動滯後

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 
} 

} 

回答

8

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.