Thursday, March 26, 2015

My First iOS Application using Swift

Introduction

This course demonstrates basic skills required to build a first iOS application using new Apple's SWIFT programming language. People without any prior programming experience can learn and develop the application with ease. During this course we create a simple application called Pitch Perfect. This app records a voice, adds different effects to the recorded voice(i.e. Chipmunks or Darth Vader) and plays that voice back at different speeds (i.e. normal, slow or fast).  In this post you can only learn how to create a simple application and play a movie quote at different speeds.

Read my next blog to know how to record a voice and add effects to it.

Click GitHub Repository for the complete code for this project.

Xcode Overview

  • Xcode is an IDE for developers to build iOS and OS X based applications which comes prepackage with SWIFT programming language. Read through the following links to get more understanding of Xcode and how can it be used to build iOS applications.

Application Framework

Model-View-Controller (MVC) design pattern is used to design and implement all iOS applications.
  • Model: Model represents the data of application i.e. audio file, properties of audio file.  
  • View: View is a visual representation of what user sees within the application.
  • Controller: Controls the interactions between Model and View of an application. For example when user clicks on a button then controller handles that event by triggering an action. Also controller sends a message to a view by referencing an outlet.

View Lifecycle Events


The following diagram depicts complete life cycle events of a view object i.e. before it appears on screen, appears on screen per each user request and till it goes off the screen.

View Lifecycle Diagram


Creating a new Xcode Project

  • Open Xcode and click on Create a new Xcode Project
  • Select iOS application for building mobile apps
  • Select Project template as Single View Application
  • Name the project and fill in other options as required
  • Select storage location for the project
  • New project creation is complete now.

Xcode project layout


Xcode Layout

  • Navigator: This is the place where we can browse through the resources of a specific project.
  • Editor: Files/resources can be edited from here. There are 2 different main editors mostly used in this course.
    • Standard Editor shows the content of a selected file or resource from a navigator. 
    • Assistant Editor shows the corresponding code i.e.logically attached to the selected resource shown in a standard editor. This happens only when we select the Manual or Automatic setting within the standard editor.
Standard & Assistant Editor

  • Utility: Panel which displays all attributes of a selected object from a storyboard or a resource shown in standard editor. We can also set or modify attributes of files, GUI elements of a project from here.

Default folders & files created by Xcode:


  • AppDelegate.swift
  • ViewController.swift:This file acts as a controller to navigate through the screens and responds to actions triggered by UI elements.
  • Main.storyboard: User Interface of an application is created or designed using the storyboard.
  • Images.xcassets: All images or assets used with in a project are managed from here.
  • LaunchScreen.xib:
  • SupportingFiles: Supporting project resources like for example music files are added here.

Building basic structure of an application

In this section we learned how to create a basic structure of an application like adding buttons, labels and images to the view. Also learned how to add actions within the controller to handle events triggered by the objects within a view.

Add UI elements to a view

Object Library
  • We can see the available UI elements in the Utility panel by clicking on the Show Object Library icon as shown above.
  • Select Button/Label from the Show Object Library and drag it on to the editor to add it to the view.

Align UI elements in a view

  • We can align the UI elements/objects by adding constraints. Constraints are used to specify a fixed size, aspect ratio, or position for one or more items in user interface, and specify distances or alignments between two or more items.
  • Click here to learn more about Storyboards, Constraints and Layout in Xcode.

 Run the application using iOS Simulator

  • Xcode comes with a plug in/feature called iOS simulator which is used to run our apps. There are different simulators available to run app on different versions of iPhone and iPad devices.

Add image to an object (example: button)

  • From the navigator window select images.xcassets file where xc stands for Xcode. This is used to manage images or assets of an application. 
  • Click on the + button shown at the bottom of the images.xcassets window to add a new image set as shown below.

  • Enter name for image and drag a image from PC onto either 1x or 2x or 3x boxes as per the iPhone device selected for this application.
Image set Editor
  • Select a button or object from a storyboard and open Utility panel. Click on attributes inspector icon on Utility panel and select image property to set the newly added image to the button like below. 
Attributes inspector

Blurry image issue in Xcode

  • Image looks blurry on the simulator when we use an image with lesser pixels or resolution i.e. 1x when it is expecting 2x image. 1x image is used for Non Retina phones (ex: iPhone 3G) and 2x image is used for Retina phones (ex: iPhone 4,5s and 6). The iPhone 6 Plus uses the 3x scale factor.

Vector Images

  • Vector images is a concept of creating a different sizes of an image at build time by using one image in a .pdf file. This way we don't need to maintain different assets for 1x, 2x and 3x images. Read this blog for how to use vector images in Xcode.

Actions & Outlets

  • Action: activity that is triggered when a user interacts with an object within a view.
  • Outlet: A name that is assigned to a object within the View so that actions/activities can be done to that object.
  • Read here to learn how to add an action and outlet within the view.

Strong & Weak Storage

  • Strong and weak both are keywords in iOS which allows us to manage memory for variables. 
  • Strong: "keep this in the heap until I don't point to it anymore"
    Weak: "keep this as long as someone else points to it strongly"

Optionals

  • In Swift we can declare a variable without defining it i.e. no need to assign a value to it at the time of declaration. mark is placed at the end of a variable declaration as shown below.
Optional Variables

Navigating between screens

Navigation controller helps us to navigate between two different screens of our application. To add a navigation controller to a storyboard follow the steps described below.

  • Determine which View Controller is the primary View Controller.  This can be done by selecting a ViewController and locating the arrow pointing at the View Controller in the story board or looking at the Attributes Inspector to determine if "Is Initial View Controller" is checked.
  • Select the primary view controller (should be highlighted in blue color) and then click on Editor menu to add navigation controller as shown below.

  • Add second view controller to the storyboard using Show Object Library from Utility Panel and name it as "PlaySoundsViewController.swift".
  • Select the button/object (which is used to switch screens) from primary view controller, hold Ctrl key and drag it on to the second view controller to link both views together. 
  • Select "Show" from the list of options displayed in the pop-up as shown below.
  • Add new button to play the audio within the new view.
  • You can also add code for the new ViewController by selecting it and linking it to a class.  It can be linked by selecting the class via the Identity Inspector (Note: you may need to add a new Class file to your project first).
  • Add an action to play the audio when user clicks on the button.

Renaming a View Controller

  • From the navigator select the view controller file that you wants to rename and change it's name
  • Next change the name of the class in Standard Editor
  • Click on storyboard and select view that needs to be attached to the renamed view controller class and set the class as renamed view controller from Identity Inspector.

Playing Audio (PlaySoundsViewController.swift)

AVAudioPlayer is the class used to play the audio from files. We must import AVFoundation framework to be able to access various properties and methods of this class.

Here are the steps to be followed to play the audio.

Get the path of audio file

  1. Import the audio file into your application by selecting File menu -> Add files to "project name" option.
  2. Make sure Copy Items if needed option before hitting on finish button. This will copy the audio file into the project folder instead of referencing to it from a different location.
  3. Move the audio file into "Supporting Files" folder using Navigation panel.
  4. Modify the viewDidLoad() method of view controller to get the path of the audio file using following code snippet.
          override func viewDidLoad() {
              super.viewDidLoad()

            // Do any additional setup after loading the view.
            let url = NSURL.fileURLWithPath(
                 NSBundle.mainBundle().pathForResource("movie_quote",
                     ofType: "mp3")!)
         }
    • NSBundle.mainBundle() -> Returns the path of the directory where the project is stored.
    • pathForResource() -> Retrieves the path of the directory where the audio file is stored.
    • NSURL.fileURLWithPath () -> Converts file path from string to fileURL object.

Create instance of AVAudioPlayer


  1. Declare a global variable of type AVAudioPlayer at class level.
  2. Initialize that variable in viewDidLoad() method of view controller.

Play Audio

Here is the list of methods and properties used in this project to play the audio at different speeds.
    • stop() - stops audio from playing
    • play() - plays audio
    • rate - sets the speed that the audio is played. The available range is from 0.5 for half-speed playback through 2.0 for double-speed playback.
    • currentTime - determines at what place the audio should start playing, 0.0 is the beginning.
See below for the complete code snippet for this exercise.

Class PlaySoundsViewController: UIViewController {
var audioPlayer: AVAudioPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let url = NSURL.fileURLWithPath(
            NSBundle.mainBundle().pathForResource("movie_quote",
                ofType: "mp3")!)
        var error: NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)\
        if let err = error {
            println("audioPlayer error \(err.localizedDescription)")
        } \
        audioPlayer.enableRate = true
    }

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

    @IBAction func stopAudio(sender: UIButton) {
        if let player = audioPlayer {
             player.stop()
        }
    }
    
    @IBAction func playSlowAudio(sender: UIButton) {
        if let player = audioPlayer {
            player.stop()
            player.rate = 0.5
            player.currentTime = 0.0
            player.play()
        }
    }
    
    @IBAction func playFastAudio(sender: UIButton) {
        if let player = audioPlayer {
            player.stop()
            player.rate = 2.0
            player.currentTime = 0.0
            player.play()
        }
    } 
}

Note: You can move the common code to play the the audio to a function and invoke it from both playSlowAudio and playFastAudio methods.

Keyboard Shortcuts

⌘ is the Command key, ⌥ is the Option/Alt key, and ⏎ is the Return/Enter key in the shortcut commands below:
  • Hide the left panel (navigator): ⌘0
  • Show the navigator: ⌘1 (2 through 8 work too!)
  • Hide the right panel (utilities): ⌥⌘0
  • Show utilities: ⌥⌘1 (2 through 6 work too!)
  • Show main editor/coding area only: ⌘⏎
  • Show additional coding area: ⌥⌘⏎
  • Help Documentation for a class: option + click on class name

References




Classes & Frameworks Covered

Frameworks

Classes