Develop a simple iOS mobile app (toDoList) using Swift – Part 1

Swift is an innovative new programming language for Cocoa and Cocoa Touch. Writing code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast. Swift is ready for your next iOS and OS X project — or for addition into your current app — because Swift code works side-by-side with Objective-C.

swift programming language

swift programming language

Here are some of features:

  1. Modern
  2. Designed for Safety
  3. Fast and Powerful
  4. Interactive Playgrounds
  5. Ready Today
  6. Read-Eval-Print-Loop (REPL)

Reference: https://developer.apple.com/swift/

Getting Started.

Before we start this tutorial, make sure you already setup your machine (mac) with these tools:

  1. Xcode 6.3.2 GM seed – https://developer.apple.com/xcode/downloads/ (More stable than Xcode 6.3.1).

Open Xcode and create a new Single View Application. For product name, use RevivalxSwiftToDoList 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.

Single View Application

Single View Application

RevivalxSwiftToDoList

RevivalxSwiftToDoList

Install CocoaPods using terminal. What is CocoaPods?

CocoaPods manages library dependencies for your Xcode projects.

The dependencies for your projects are specified in a single text file called a Podfile. CocoaPods will resolve dependencies between libraries, fetch the resulting source code, then link it together in an Xcode workspace to build your project.

Ultimately the goal is to improve discoverability of, and engagement in, third party open-source libraries by creating a more centralised ecosystem.

Reference: https://guides.cocoapods.org/using/getting-started.html

Open your terminal and type this command.

sudo gem install cocoapods
sudo gem install cocoapods

sudo gem install cocoapods

Go to your directory and initialize your pod using this command.

cd /Users/MNurdin/Documents/iOS/RevivalxSwiftToDoList
pod init
pod init

pod init

Open your finder and edit pod file (Podfile) with these one.

# Uncomment this line to define a global platform for your project
#platform :ios, '8.0'
use_frameworks!

pod 'HanekeSwift'
pod 'Parse'
pod 'ParseFacebookUtils'
pod 'ParseUI'

target 'RevivalxSwiftToDoList' do

end

target 'RevivalxSwiftToDoListTests' do

end

The reasons why we need these libraries because

Go back to your terminal and run pod install to install all the dependencies. It takes a few of minutes to download.

pod install
Pod install.

Pod install.

After finish downloading, open RevivalxSwiftToDoList.xcworkspace file, not RevivalxSwiftToDoList.xcodeproj because we want to use the pod.

Storyboards and interface builder

Set to Compact Width | Any Height.

Compact Width | Any Height

Compact Width | Any Height

Delete ViewController.swift and ViewController on the Main.Storyboard. Drag a Table View Controller and View Controller to Main.Storyboard.

Main.Storyboard

Main.Storyboard

Select Table View Controller and navigate to Attributes inspector. Tick Is Initial View Controller.

Attributes inspector

Attributes inspector

Select the Table View Controller again and in the menu go to Editor > Embed In > Navigation Controller. This adds a Navigation Controller to the storyboard with an initial scene.

Editor > Embed In > Navigation Controller

Editor > Embed In > Navigation Controller

Select the Navigation Item under the Table View Controller, and in the Attributes Inspector type To Do List as the Title.

Navigation Item

Navigation Item

From the Object Library, drag a Bar Button Item to the right of the navigation bar on the Table View Controller. Select the Bar Button Item (which has a default value of “Item”) and in the Attributes Inspector, in the Identifier option, choose Add. This will change the button to the add symbol (+).

Bar Button Item

Bar Button Item

Select the Table View Controller, press control button and drag to View Controller like image below. We added a segue.

Segue

Segue

Name it MySegue in Show the Attributes Inspector > Identifier.

Storyboard Segue

Storyboard Segue

Result

Main.Storyboard

Main.Storyboard

Continue on next post, http://blog.revivalx.com/2015/08/12/develop-a-simple-ios-mobile-app-todolist-using-swift-part-2/.

Image cache using Haneke.

Haneke is a lightweight generic cache for iOS written in Swift 1.2. It’s designed to be super-simple to use. https://github.com/Haneke/HanekeSwift

Open Xcode6 and create a new Single View Application. For product name, use RevivalxHanekeSwift 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.

Single View Application

Single View Application

Choose options for your new project

Choose options for your new project

Download Haneke for Swift from Github here, https://github.com/Haneke/HanekeSwift. Copy and drag Haneke library into your project.

Finder

Finder

Xcode6 – Project info

Xcode6 – Project info

Don’t forget to set Embedded Binaries. Target > RevivalxHanekeSwift > SwiftEmbedded Binaries.

Embedded Binaries

Embedded Binaries

Set to Compact Width | Any Height.

Compact Width | Any Height

Compact Width | Any Height

Go to the Storyboard and drag an Image View to the main View. Select the Image View and go to the Size inspector and fill in the following values.

 

And image mode change to Aspect Fill.

Image View mode

Image View mode

Open document outline, select the Image View again and set constraint to Center Horizontally in ContainerCenter Vertically in ContainerTop space to Top Layout Guide and Leading Space to Container Margin.

Document Outline and Constraints

Document Outline and Constraints

The Storyboard will look like this.

Main.Storyboard

Main.Storyboard

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Image View to the ViewController class and create the following Outlet.

Image View property outlet

Image View property outlet

Go to the ViewController.swift file, import Haneke and change the viewDidLoad method.

import UIKit
import Haneke

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let url = NSURL(string: "https://graph.facebook.com/10204521055439574/picture?type=large")
        //profilePhotoImage.contentMode = .ScaleAspectFill
        imageView.hnk_setImageFromURL(url!)
    }

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


}

Your output.

iOS simulator

iOS simulator

Build and Run the project. You can download the source code here, https://github.com/datomnurdin/RevivalxHaneke.

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

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