1

I am trying to set up a feed page with a UITableView, retrieving all the JSON data from Node.js API.

Looks like it it is working, but it is very slow and sometimes does not retrieve all the images. Is there a way to make it work completely, and to optimize the code?

import UIKit




class homeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {



@IBOutlet weak var tableView: UITableView!


var jsonData : [NSDictionary] = [NSDictionary]()
var imageUrls: NSDictionary = NSDictionary()
var urlsArray: [NSURL]! = [NSURL]()


override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.reloadData()

    let qualityOfServiceClass = QOS_CLASS_BACKGROUND
    let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
    dispatch_async(backgroundQueue, {
        println("This is run on the background queue")
        self.refreshData()
        self.getImage()

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            println("This is run on the main queue, after the previous code in outer block")
            self.tableView.reloadData()
        })
    })




}

override func viewWillAppear(animated: Bool) {



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}





func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


   return jsonData.count



}



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


    var type = jsonData[indexPath.row]["type"] as! Int

    if type == 1 {


        println("Type= \(type)")

        let cell1 : cellTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! cellTableViewCell


        //If images url are retrieved, load them. Otherwise, load the placeholders
        if self.urlsArray.isEmpty == false {

            println("Tiè: \(self.urlsArray[indexPath.row])")


            if let data = NSData(contentsOfURL: self.urlsArray[indexPath.row]) {

                    cell1.profileImg?.image = UIImage(data: data)

                }

        } else {

            cell1.profileImg?.image = UIImage(named: "placeholder.png")

        }


        cell1.testLbl.text = (self.jsonData[indexPath.row]["author"] as? String)!

        return cell1

    } else {


        let cell2 : cell2TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell2") as! cell2TableViewCell


        return cell2
    }
}


func refreshData()   {


    let requestURL = NSURL(string:"http://adall.ga/api/feeds/author/mat/0")!


    var request = NSMutableURLRequest(URL: requestURL)
    request.HTTPMethod = "GET"



    request.addValue(userToken, forHTTPHeaderField: "tb-token")

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithRequest(request) {
        data, response, error in


        println(response)

        var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)

        println(dataString)

        //let jsonResult : NSDictionary = (NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary)!
        //jsonData = (NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: nil) as? NSArray)!


        self.jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as! [NSDictionary]



    }

    task.resume()

    var index: Int
    for index = 0; index < 10000; ++index {
        print("Index: \(index), Task state: \(task.state)")
    }
}



func getImage() {

    var i = 0

    for jsonSingleData in jsonData {

        let author = jsonSingleData["author"] as! String


        let requestURL2 = NSURL(string: "http://adall.ga/api/users/" + author + "/image")!

        println("request: \(requestURL2)")


        var request2 = NSMutableURLRequest(URL: requestURL2)
        request2.HTTPMethod = "GET"


        request2.addValue(userToken!, forHTTPHeaderField: "tb-token")


        let session2 = NSURLSession.sharedSession()

        let task2 = session2.dataTaskWithRequest(request2) {
            data, response, error in


            println("response= \(response)")


            var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println(dataString)



            self.imageUrls = (NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary)


            //check if exists
            let imageUrl = self.imageUrls["url"] as! String

            let url = NSURL(string: "http://" +  imageUrl)

            self.urlsArray.append(url!)

            println(self.urlsArray)


            }

        task2.resume()


    }
}
dpstart
  • 1,018
  • 1
  • 10
  • 25

1 Answers1

1

Hi for loading images you can use SDWebImage it will take care of all the heavy lifting and caching for you. here's how:

// Here we use the new provided sd_setImageWithURL: method to load the web image
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                             completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {... completion code here ...}];

Here's a Swift example

Community
  • 1
  • 1
Or Ron
  • 2,313
  • 20
  • 34
  • Added a swift example. I really advise you to use this lib. – Or Ron Aug 16 '15 at 11:20
  • Can you make me an example of usage related to my code? Thank you – dpstart Aug 16 '15 at 11:43
  • Inside the swift example you can see. it's just what you need. You import the SDWebimagecache category and then you use it with url and completion block. its literally that easy. In your cell for indexpath activate that on the UIImageView's and let them handle the loading with the help of this category. – Or Ron Aug 16 '15 at 11:46
  • If this answer helped you please mark as correct and upvote. Thanks. – Or Ron Aug 16 '15 at 12:40
  • Of course. Only one question: how can I know if urlArray is already full and I can reload the data in the table? Thank you – dpstart Aug 16 '15 at 12:43