Ich ziehe Daten aus einer JSON-API Rufen Sie die Tabellenansicht auf, ist aber sehr langsam und bleibt beim Scrollen unten, wie beschleunige ich das Laden der Tabelle. Ich bin neu zu schnell und Xcode irgendwelche Tipps wäreSwift tableView langsame und rollende Verzögerung
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
}
}