How to Build Your First App with Swift

By ongraph
September 9, 2014 | 2196 Views

Latest Industry insights to keep you updated on the latest happenings.

In the previous blog, we have discussed the new features in Swift and comparison with Objective-C. I hope before starting with this tutorial you have started with the great book on Swift provided by Apple.

In this tutorial we will learn how to make a simple iOS app.  This tutorial is written in such a manner that it will be useful for complete beginners and experienced iOS developers transitioning to Swift.

For this tutorial we need the latest Xcode 6 beta. For this tutorial you don’t need any Swift or Objective-C experience, although it will be helpful if you have some programming experience.

NOTE : At the time of writing this Xcode 6 is still in beta mode.

APP OVERVIEW

Today we will create a application that works as a stopwatch.

APP CREATION

Lets begin by creating a new project for the sample app. Launch Xcode and in the welcome window select the respective option.

After selecting the option for new Xcode project a new window will appearing offering different types of app. So from those options Select Single View Application template in the application category under iOS section.

Click Next and in the project name field put the name you would like to give your application. Select the language as Swift and device as iPhone for now.

On clicking next Xcode will ask for a place to save you project select that and click create.

Now as you see the project structure on left hand side in Xcode. You will see a a storyboard file named as Main.storyboard and two Swift files one is AppDelegate.swift and other is ViewController.swift.

Now open up the Main.storyboard file. It will open up a storyboard file of you app for you. Storyboard. You will create the user interface of your iOS application in Storyboard. Xcode comes with a build in tool called interface builder that allows you to edit storyboards in nice way. With interface builder you can lay out all of your buttons, textfields, labels and other controls by simply dragging and dropping .

 

Lets cover every section of our screen in Xcode.

1. On the left hand side is project navigator where you can se the files in your project.

2. On the left of the interface builder in you Document outline, where you can take a glance at each view controller or i should say screen.

3. There’s an array on the left hand side of your view controller. This indicates that this view controller is your initial view controller or simply the first view or screen that plays when you app starts up.

4. On the bottom of Interface Builder you will see something saying “w Any”, “h Any”. this means you are editing the layout for you app in a way that it should work on any sized user interface.

5. On top of view controller you will see three small icons representing view controller, first responder and exit.

6. On the bottom of IB there are four icons related to auto layout.

7. On the bottom right of IB are LIBRARIES.

-> Now from the libraries search for textfields and drag and drop two textfields on you view at 40px distance from top and 20px distance from left, one below another or side by side as u like.

 

Check Your View Controller : 

Lets take a look at view controller of our app.

Open ViewController.swift. this is the Swift code for your single view controller in you app which is responsible for managing communication between you views and models.

The file has the following code

import UIKit
class ViewController: UIViewController
{                           
    @IBOutlet var firstNumTxf: UITextField!
    @IBOutlet var secondNumTxf: UITextField!
   
    override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

You saw something new in the code.

1. iOS is made of many frameworks each of which contains different set of code. Before you can code from a framework in you app. You have to import jt like its done here.

2. This is the first example you have seen of a class subclassing another.

3. Whenever you override a function you use override keyword in Swift.

4. didRecieveMemoryWarning method is called when device is running low on memory.

 

Coding :

1. Navigate to Object Library, drag and drop UILabel to View Controller. Then align the label horizontally centred to the View Controller. Using theAttributes Inspector enter the label text as 00:00:00, change the colour to White

2. Now drag and drop two buttons for starting and stopping the timer. Change the button text to Start and Stop respectively and set the Text Color to white.

3. add a IBOutlet for UILabel.

  @IBOutlet var displayTimeLbl: UILabel

4. Then add two IBActions method for the two buttons, Start and Stop.

  @IBAction func start(sender: AnyObject) 
{
}
@IBAction func stop(sender: AnyObject)
 {
}

5. Drag and connect the UILabel with the IBOutlets, similarly connect IBActions with the buttons and specify the event as Touch Up Inside.

 

LOGIC

Navigate to ViewController.swift file and new function name as updateTime. This function will be used for calculating the time in minutes, seconds and fraction of milliseconds.

Add a new class level variable to the class for storing the start time.

      var startTime = NSTimeInterval()

Then add the following code in updateTime method. This is used for calculating the StopWatch time and assigning the value to the UILabel.

       func updateTime()
      {
            var currentTime = NSDate.timeIntervalSinceReferenceDate()
//Find the difference between current time and start time.
     var elapsedTime: NSTimeInterval = currentTime – startTime
//calculate the minutes in elapsed time.
     let minutes = UInt8(elapsedTime / 60.0)
     elapsedTime -= (NSTimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
     let seconds = UInt8(elapsedTime)
     elapsedTime -= NSTimeInterval(seconds)
//find out the fraction of milliseconds to be displayed.
     let fraction = UInt8(elapsedTime * 100)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
     let strMinutes = minutes > 9 ? String(minutes):“0” + String(minutes)
     let strSeconds = seconds > 9 ? String(seconds):“0” + String(seconds)
     let strFraction = fraction > 9 ? String(fraction):“0” + String(fraction)
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
     displayTimeLbl.text = “\(strMinutes):\(strSeconds):\(strFraction)”
}

Add a new class level NSTimer variable as shown below.

var timer = NSTimer()

Navigate to Start IBAction function and add the following the code.

  @IBAction func start(sender: AnyObject) 
{
     timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector(“updateTime”), userInfo: nil, repeats: true)
     startTime = NSDate.timeIntervalSinceReferenceDate()
}

This would start a timer and it repeats at regular time interval of 0.01. Here we specify

the “updateTime” function which gets called regularly after the specified interval. We also

initialise the startTime variable to the current time. Now when the user taps on Stop button, timer is invalidated and set to nil.

@IBAction func stop(sender: AnyObject) 
{
     timer.invalidate()
     timer == nil
}

If you try to run this app on the simulator, you should notice the start and stop functionality works and time is getting displayed in the Label. But the user can repeatedly tap the Start button. So when the clock is running if the user taps the Start button, clock restarts again. We can prevent this by adding the following check to start the timer only when the timer is not running.

@IBAction func start(sender: AnyObject)
{
     if !timer.valid 
{
     timer =      NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector(“updateTime”), userInfo: nil, repeats: true)
     startTime = NSDate.timeIntervalSinceReferenceDate()
}

Monthly industry insights to keep you updated on latest happenings

Follow us on Twitter
Follow us on Facebook
Follow us on Linkedin