ienamo ienamo - 4 months ago 18
iOS Question

tableview slow the app , and take time to fetch data - swiftyJSON

I'm trying to get data from url , using swiftyJSON/Almofire :

here is my code :

import UIKit
import Alamofire
import SwiftyJSON

class NewsTableViewController: UITableViewController {


var arrRes = [[String:AnyObject]]() //Array of dictionary

override func viewDidLoad() {
super.viewDidLoad()


Alamofire.request(.GET, "myURL**").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
print(swiftyJsonVar)
if let resData = swiftyJsonVar[].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.tableView.reloadData()
}
}
}


self.navigationController?.navigationBar.tintColor = UIColor(red:0.47, green:0.07, blue:0.55, alpha:1.00)

}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier("bCell", forIndexPath: indexPath) as! TableViewCell

var dict = arrRes[indexPath.row]

if let strImage = arrRes[indexPath.row]["image"] as? String{
if let data = NSData(contentsOfURL: NSURL(string:strImage.encodeUTF8()!)!) {
cell.imgView.image = UIImage(data: data)
}
}


cell.titleLabel?.text = dict["title"] as? String
return cell

}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arrRes.count
}


the tableview became so slow when I scroll , and it takes time to fetch data!, do you have any idea why it behave like this ,
also I followed tutorial for this , and he didn't mention why he used Almofire here , and what do you call fetching data from JSON url ? is it called "REST API" ? so I could make good search on it , and have a good start as I am a beginner.

Answer

Because you get Image from URL in main thread:

        if let data = NSData(contentsOfURL: NSURL(string:strImage.encodeUTF8()!)!) {
            cell.imgView.image = UIImage(data: data)
        }

You should do it in background thread and when you get data return in to main thread:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
       if let data = NSData(contentsOfURL: NSURL(string:strImage.encodeUTF8()!)!) {
             dispatch_async(dispatch_get_main_queue(), ^{
                image = UIImage(data: data)
            });
        }
});