I'm currently developing a JSON TableView with the information from my database (some products with the image and their names). Everything is fine but it's very slow when I scroll down (or up). I have made a lot of research regarding this topic but I have tried their codes and I still don't know how to store the images in the cache to speed up the TableView.
Here is my code:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BuscarCellTableViewCell
if searchController.active {
cell.nombre.text = searchResults[indexPath.row].nombre
cell.marca.text = searchResults[indexPath.row].marca
if let url = NSURL(string: searchResults[indexPath.row].imagen) {
if let data = NSData(contentsOfURL: url) {
cell.imagen.image = UIImage(data: data)
}
}
}
else {
cell.nombre.text = productos[indexPath.row].nombre
cell.marca.text = productos[indexPath.row].marca
if let url = NSURL(string: productos[indexPath.row].imagen) {
if let data = NSData(contentsOfURL: url) {
cell.imagen.image = UIImage(data: data)
}
}
}
return cell
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// Define the initial state (Before the animation)
cell.alpha = 0.25
// Define the final state (After the animation)
UIView.animateWithDuration(1.0, animations: { cell.alpha = 1 })
}
func getLatestLoans() {
let request = NSURLRequest(URL: NSURL(string: LoadURL)!)
let urlSession = NSURLSession.sharedSession()
let task = urlSession.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
let res = response as! NSHTTPURLResponse!
var err: NSError?
if error != nil {
println(error.localizedDescription)
}
// Parse JSON data
self.productos = self.parseJsonData(data)
// Reload table view
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
})
task.resume()
}
func parseJsonData(data: NSData) -> [Producto] {
var productos = [Producto]()
var error:NSError?
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
// Return nil if there is any error
if error != nil {
println(error?.localizedDescription)
}
// Parse JSON data
let jsonProductos = jsonResult?["lista_productos"] as! [AnyObject]
for jsonProducto in jsonProductos {
let producto = Producto()
producto.nombre = jsonProducto["nombre"] as! String
producto.imagen = jsonProducto["imagen"] as! String
productos.append(producto)
}
return productos
}
How can I speed up my TableView when scrolling down the "products" from my JSON file?
Thanks in advance,
Regards.