UICollectionView 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 RevivalxCollectionView 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 UICollectionView inside View Controller.

UICollectionView

UICollectionView

Main.storyboard

Main.storyboard

Set Collection View Cell Size to 130 width and 130 height.

Collection View

Collection View

Set Collection Reusable View Identifier to ImageCell.

Collection Reusable View Identifier

Collection Reusable View Identifier

Drag UIImageView to UICollectionViewCell.

UIIMageView

UIIMageView

Main.storyboard

Main.storyboard

Set constraints for each UICollectionViewCell.

UICollectionViewCell

UICollectionViewCell

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

Create a new file. File > New > File.

Create a new file

Create a new file

Select Source (iOS) > Cocoa Touch Class > Next.

Choose a template for your new file

Choose a template for your new file

Select UICollectionViewCell and click Next. Then click Create.

Choose a template for your new file

Choose a template for your new file

Go to the ViewController.swift file and import Alamofire.

import Alamofire

Add UICollectionViewDataSource,UICollectionViewDelegate and UICollectionViewDelegateFlowLayout to ViewController class.

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

Add the following properties.

var datas: [JSON] = []
@IBOutlet var collectionView: UICollectionView!

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.collectionView.reloadData()
                }
            }
        }

Add three methods after didReceiveMemoryWarning method.

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //#warning Incomplete method implementation -- Return the number of items in the section
        return datas.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as CollectionViewCell

        cell.data = self.datas[indexPath.row]
        return cell
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
        return 1
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
        return 3
    }

Go to the CollectionViewCell.swift file and import Haneke.

import Haneke

Add the following properties.

@IBOutlet weak var imageView:UIImageView!

Initilize JSON object after outlet property.

var data:JSON?{
        didSet{
            self.setupData()
        }
    }

Finally we add setupData method after initilize JSON object.

func setupData(){

        if let urlString = self.data?["images"]["standard_resolution"]["url"]{
            let url = NSURL(string: urlString.stringValue)
            self.imageView.hnk_setImageFromURL(url!)
        }

    }

Bind collectionView outlet property with UICollectionView in ViewController.

Outlet property

Outlet property

Bind CollectionViewCell and imageView as well.

CollectionViewCell

CollectionViewCell

imageView

imageView

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

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/RevivalxCollectionView

4 thoughts on “UICollectionView Tutorial in Swift using Alamofire, Haneke and SwiftyJSON

  1. hi!
    thanks for your tutorial! the quality is good but you can improve it : i suggest you to add a video or to make a build and run app not just at the end.
    Moreover i downloaded your project (uicollectionview tutorial in swift using alamofire, haneke and swiftyJSON) and it doesn’t work. First the file SwiftyJSON was empty, and when I build and run your project, build succeeds but after that nothing happens (no message in console, no app is launched in the emulator).
    Thanks again for your tutorial 🙂

    Matt

Leave a Reply

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