UITableView Tutorial in Swift using Alamofire, Haneke and SwiftyJSON

In this tutorial, I will show you how to use Alamofire, Haneke and SwiftyJSON with UITableView.

Alamofire - Elegant Networking in Swift

Alamofire – Elegant Networking in Swift

AFNetworking is one of the most popular third-party libraries on iOS and OS X and is one of the most widely-used open source projects on Github with over 14K stars and 4K forks.

Recently the creator and maintainer of AFNetworking, Mattt Thompson, released a new networking library like AFNetworking, but designed specifically to use modern Swift conventions and language features: Alamofire.

Reference: http://www.raywenderlich.com/85080/beginning-alamofire-tutorial

Haneke - A lightweight generic cache for iOS written in Swift with extra love for images.

Haneke – A lightweight generic cache for iOS written in Swift with extra love for images.

Haneke is a lightweight generic cache for iOS written in Swift. It’s designed to be super-simple to use.

Haneke provides a memory and LRU disk cache for UIImage, NSData, JSON, String or any other type that can be read or written as data. Particularly, Haneke excels at working with images. It includes a zero-config image cache with automatic resizing. Everything is done in background, allowing for fast, responsive scrolling. Asking Haneke to load, resize, cache and display an appropriately sized image is as simple as:

imageView.hnk_setImageFromURL(url)

Reference: https://github.com/Haneke/HanekeSwift

SwiftyJSON makes it easy to deal with JSON data in Swift.

Open your Xcode6 and select Create a new Xcode project. Select Single View Application and click Next.

Single View Application

Single View Application

For product name, use RevivalxTableView and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices. Click Next. Select workspace and click Create.

Xcode6 New Project

Xcode6 New Project

Open Main.storyboard and drag UITableView inside View Controller.

UITableView

UITableView

Main.storyboard

Main.storyboard

Set Prototype Cells from 0 to 1.

Prototype Cells

Prototype Cells

Then set Row Height for Table View Cell to 320.

Table View Cell

Table View Cell

Drag UIImageView to UITableViewCell.

UIIMageView

UIIMageView

Drag UILabel to UIImageView. SetUILabel background colour to black and font colour to white.

Main.storyboard

Main.storyboard

Set Label tag to 100.

label tag

label tag

Set Image View tag to 101.

image view tag

image view tag

Set constraints for each UIImageView and UILabel.

UIImageView

UIImageView

UILabel

UILabel

Now you need register your application here, https://instagram.com/developer/.  Enter your Application Name, Description and Website. Enter Captcha and click Register.

Instagram developer

Instagram developer

Copy Client ID and save it into save place. Now get data from instagram API. Run this sample URL in your web browser. XXXXXXXXXXXXXXXXXXXXXXXXX is your Client ID. We use Malaysia tag for example.

https://api.instagram.com/v1/tags/malaysia/media/recent?client_id=XXXXXXXXXXXXXXXXXXXXXXXXX

The data we will use for this tutorial is images (standard_resolution) and captions.

Instagram data

Instagram data

Then we download Alamofire (https://github.com/Alamofire/Alamofire), Haneke (https://github.com/Haneke/HanekeSwift) and SwiftyJSON (https://github.com/SwiftyJSON/SwiftyJSON) from github website. Copy Alamofire, Haneke and SwiftyJSON into project.

Finder

Finder

Xcode6 - Project info

Xcode6 – Project info

Go to the ViewController.swift file and import Alamofire and Haneke.

import Alamofire
import Haneke

Add UITableViewDelegate and UITableViewDataSource to ViewController class.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

Add the following properties.

var datas: [JSON] = []
@IBOutlet weak var tableView: UITableView!

Change the viewDidLoad method to

Alamofire.request(.GET, "https://api.instagram.com/v1/tags/malaysia/media/recent?client_id=XXXXXXXXXXXXXXXXXXXXXXXXX").responseJSON { (request, response, json, error) in
            if json != nil {
                var jsonObj = JSON(json!)
                if let data = jsonObj["data"].arrayValue as [JSON]?{
                    self.datas = data
                    self.tableView.reloadData()
                }
            }
        }

Add three methods after didReceiveMemoryWarning method.

// MARK: - Table view data source
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return datas.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("ImageCell", forIndexPath: indexPath) as UITableViewCell //1
        let data = datas[indexPath.row]
        if let captionLabel = cell.viewWithTag(100) as? UILabel {
            if let caption = data["caption"]["text"].string{
                captionLabel.text = caption
            }
        }
        if let imageView = cell.viewWithTag(101) as? UIImageView {
            if let urlString = data["images"]["standard_resolution"]["url"].string{
                let url = NSURL(string: urlString)
                imageView.hnk_setImageFromURL(url!)
            }
        }
        return cell
    }

Bind tableView outlet property with UITableView in ViewController.

Outlets

Outlets

Set identifier as ImageCell.

TableViewCell as ImageCell

TableViewCell as ImageCell

Finally we need to set Referencing Outlets (dataSource and delegate) to TableView.

Referencing Outlets

Referencing Outlets

Run your project and you output will get like this one.

Final output iOS app

Final output iOS app

Source code: https://github.com/datomnurdin/RevivalxUITableView

14 thoughts on “UITableView Tutorial in Swift using Alamofire, Haneke and SwiftyJSON

  1. This is just what I needed – SwiftyJSON and AlamoFire in a Swift project – the Instagram API is an incredible bonus 🙂 This tutorial was incredibly helpful, thank you so much for sharing!

    1. Hello Rob. I have JSON response which has topic and replies array. Each topic contains any number of replies or nothing . I have created model for it Topic and replies. My Question is how can i display it on tableView . Like Question1 and replies , Question 2 and replies , Question 3 and(if no reply) Add invite button. Can you ps explain me logic ..

  2. Cool project. I was wondering if you know how to get it to be aspect fit and get the image in the middle of the tableview. For me it always looks like the imageview is wider than the tableview.

  3. Hi!

    Is there any update for Swift 2.0 ?
    My error is “Cannot invoke initializer for ‘JSON’ with an argument list of type ‘(Result)’

    Thanks for the tutorial

  4. Hi! Great tutorial! I have followed along for an app I’m creating but i get stuck at transferring the image downloaded in prepareforsegue. I’m able to segue everything else i pull from my json file but I get stuck with the code for the image. Any help would be very appreciated.

Leave a Reply

Your email address will not be published. Required fields are marked *