iOS Swift Basics Tutorial: Protocols and Delegates

Here a cool tutorial protocols and delegates using Swift. This link will explain more details about the delegate, https://www.andrewcbancroft.com/2015/03/26/what-is-delegation-a-swift-developers-guide/.

Getting started.

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

  1. Xcode 7.1: https://developer.apple.com/xcode/

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

RevivalxSwiftProtocolDelegate

RevivalxSwiftProtocolDelegate

Go to Main.Storyboard and set to Compact Width | Any Height.

Compact Width | Any Height

Compact Width | Any Height

Select View Controller in storyboard and select Editor > Embed In > Navigation Controller.

Embed in Navigation Controller.

Embed in Navigation Controller.

Navigation Controller.

Navigation Controller.

Go to Object Library and drag/drop a new View Controller into storyboard.

Main.Storyboard.

Main.Storyboard.

Go to Object Library again and drag/drop Bar Button Item into first view controller. Change the Bar Button Item icon to plus icon. Then press control button and at the same time drag the mouse/pointer to second view controller. Select show under Action Segue. Finally add Navigation Item into second view controller and name it for both view controllers.

Main.Storyboard.

Main.Storyboard.

Drag and drop Label and TextField from Object Library into both view controllers. Make sure it similar with example below. Don’t forget to set autolayout for each label and textfield. If you not really understand about the autolayout, feel free to read this tutorial. http://www.raywenderlich.com/83129/beginning-auto-layout-tutorial-swift-part-1

Main.Storyboard.

Main.Storyboard.

Create a new ViewController.swift (UIViewController).

Xcode 6.4 – New File.

Xcode 6.4 – New File.

Cocoa Touch Class

Cocoa Touch Class

UIViewController

UIViewController

Project navigator.

Project navigator.

Select second view controller and make sure you attach SecondViewController into each controllers in Identity inspector.

Identity inspector -UIViewController

Identity inspector -UIViewController

Select the Assistant Editor and open SecondViewController.swift. Ctrl and drag from the Text Field to the ViewController class to create the following outlet.

TextField outlet.

TextField outlet.

Ctrl and drag from the Button and create the following action.

Button outlet.

Button outlet.

Open ViewController.swift. Ctrl and drag from the Label to the ViewController class to create the following outlet.

Label outlet.

Label outlet.

Select Attribute inspector and name it as SecondSegue in Identifier field.

Storyboard segue.

Storyboard segue.

Go to the SecondViewController.swift file and replace with this code.

import UIKit

protocol DataEnteredDelegate{
    func userDidEnterInformation(info: NSString)
}

class SecondViewController: UIViewController {

    @IBOutlet weak var txtData: UITextField!
    var delegate:DataEnteredDelegate? = nil
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func sendData(sender: AnyObject) {
        if (delegate != nil){
            let data: NSString = txtData.text
            
            delegate!.userDidEnterInformation(data)
            self.navigationController?.popViewControllerAnimated(true)
        }
    }
}

Open ViewController.swift and update the with this code.

import UIKit

class ViewController: UIViewController, DataEnteredDelegate {

    @IBOutlet weak var lblResult: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    func userDidEnterInformation(info: NSString) {
        lblResult.text = info as String
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "SecondSegue" {
            let secondViewController: SecondViewController = segue.destinationViewController as! SecondViewController
            secondViewController.delegate = self
        }
    }
}

Run your project. Feel free to check out my source code here, https://github.com/datomnurdin/RevivalxSwiftProtocolDelegate.

Using 3rd-party libraries using CocoaPods

What is Cocoapods?

CocoaPods is the dependency manager for Swift and Objective-C Cocoa projects. It has almost ten thousand libraries and can help you scale your projects elegantly.

Reference: https://cocoapods.org/

CocoaPods

CocoaPods

Open your terminal and type this command:

sudo gem install cocoapods
Installation CocoaPods via terminal.

Installation CocoaPods via terminal.

Init your xcode project.

pod init

Search for pod file in your xcode project (podfile). Then list the dependencies in a text file named Podfile in your Xcode project directory:

platform :ios, '8.0'
use_frameworks!

target 'MyApp' do
  pod 'AFNetworking', '~> 2.5'
  pod 'ORStackView', '~> 2.0'
  pod 'SwiftyJSON', '~> 2.1'
end

Now you can install the dependencies in your project:

pod install
pod install

pod install

Open your *.xcworkspace.

HelloWorld.xcworkspace

HelloWorld.xcworkspace

You can verify it here to make sure your dependencies already installed.

Pod

Pod

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

Looking for Universities or Colleges to Train iOS SWIFT 5 days full courses for FREE

Looking for Universities or Colleges to Train iOS SWIFT 5 days full courses for FREE. Macbooks will be provided during training. Only 20 Seats per University. NO strings attached. We will train for FREE ONLY.

Requirements:
Participants must be Malaysian 18 and above (Student or Staff). Local Universities eligible only (All over Malaysia, including Sabah & Sarawak)

Training Dates: Will be decide by each University. This training program ends Dec 2015.

Location: Your Universiti or College. Just provide us a room and if you can provide meals that would be great!

What Participants will Learn in 5 days

  1. Swift Language programming Foundation
  2. Creating iOS apps Foundation
  3. UI/UX programming
  4. Wire framing for an iOS app
  5. IOS Database programming
  6. IOS Sensors programming
  7. Apple Watch Programming using REAL Device
  8. How to port to Apple App Store

Be the First to Train and Develop for Apple Watch in Malaysia!!!

Please contact caspian training@caspian.my

Encrypt image using AESCrypt-ObjC and Swift.

AESCrypt is a simple to use, opinionated AES encryption / decryption Objective-C class that just works. AESCrypt uses the AES-256-CBC cipher and encodes the encrypted data with base64.

https://github.com/datomnurdin/AESCrypt-ObjC

Open Xcode and create a new Single View Application. For product name, use RevivalxSwiftAESCrypt 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 AESCrypt-ObjC for Swift from Github here, https://github.com/Gurpartap/AESCrypt-ObjC. Copy the library into your project.

AESCrypt-ObjC

AESCrypt-ObjC

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.

Show the Size inspector

Show the Size inspector

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

Continue..