Swift - Populating UITableView with data from API

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()


    }
}

Answers


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


Need Your Help

how to display popover click on a tableview cell in ipad

objective-c ipad uipopovercontroller

i am using a TableView in my application where i want a Pop over View when i clicked on a tabel cell, all the content which is in table Cell should display in a pop over view so plz suggest me how to

Is it possible to tell if there are any ongoing 'GET' requests with javascript?

javascript jquery

Is it possible to tell if there are any ongoing 'GET' requests with javascript?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.