You are on page 1of 118

iOS

8 Programming with Swift



A Step By Step Guide Book for Beginners.
Create Your Own App in One Day!

Kevin Lyn.

Copyright 2015 by Kevin Lyn.

All rights reserved. No part of this publication may be reproduced, distributed, or
transmitted in any form or by any means, including photocopying, recording, or other
electronic or mechanical methods, without the prior written permission of the author,
except in the case of brief quotations embodied in critical reviews and certain other
noncommercial uses permitted by copyright law.
Disclaimer
While all attempts have been made to verify the information provided in this book, the
author doesnt assume any responsibility for errors, omissions, or contrary interpretations
of the subject matter contained within. The information provided in this book is for
educational and entertainment purposes only. The reader is responsible for his or her
own actions and the author does not accept any responsibilities for any liabilities or
damages, real or perceived, resulting from the use of this information.

Contents

Book Description
Introduction
Chapter 1: Definition
Chapter 2: Getting Started with iOS 8 Swift Programming
Chapter 3: Variables and Constants in Swift
Chapter 4: Type Annotations
Chapter 5: Tuples in Swift
Chapter 6: Enumerations in Swift
Raw Values
Chapter 7: UIAlertView in Swift
Chapter 8: NSTimer in Swift
Project Setup
Coding the Timer
Stopping the NSTimer
Clearing the NSTimer
Chapter 9: Swift and PHP
Posting from Swift to PHP
How to Get the Status of the HTTP Code
Chapter 10: Connecting to iTunes Search API
How to Connect the User Interface
How to Make the API Request
How to Prepare for the Response
How to Update the Table View UI
Chapter 11: Image Loading and Caching Asynchronously

Chapter 12: Using Objective-C classes in Swift


Chapter 13: Animations in Swift
Container View Transitions
Chapter 14: Creating an Audio Player with Swift
Creating the User Interface
Action Methods
Creation and Initialization of AVAudioPlayer Object
Implementation of the AVAudioPlayerDelegate Protocol Methods
Conclusion

Book Description


This book begins by explaining the iOS 8 and the Swift programming language, including
their origin and functionality. Explanation on how to get started with Swift is available,
including setting up the environment.
Variables, constants, and Tuples which are used to store values in Swift have been
explored. On reading this book, you will get to understand how to create an NSTimer for
your iOS app. Enumerations and Type annotations in Swift have also been explored in
detail. You will get to understand how to send some post request to a PHP script, using a
server. You will also know how to load images into your Swift app asynchronously.
Connecting your app to the iTunes Search API is also examined. The process of importing
Objective-C classes into Swift has been explained. Animations and playing audio in Swift
have also been discussed. Programs illustrating how to achieve the above features have
been included, as well as pictures illustrating the same.
The language used in this book is very simple, so that it suits both the experts and the
beginners. The following topics have been discussed:

Definition
Getting Started with Swift
Variables and Constants.
Type Annotations

Tuples
Enumerations
UIAlertView
NSTimer in Swift
Swift and PHP
Connecting to iTunes Search API
Image Loading and Caching Asynchronously
Using Objective-C Classes
Animations
Creating an Audio Player

Introduction

iOS 8 has shown improved support for amazing features which were not supported in iOS
7. This explains the need for the creation of iOS 8 apps, and therefore the need to learn
Swift.

Recently, Apple Inc released iOS 8 into the market. This followed a release of the Swift
programming language for the purpose of creating apps to run on devices supporting this
version of iOS. This language has shown a number of improvements in terms of
functionality compared to the Objective-C programming language.

Chapter 1:
Definition


iOS is an operating system used on Apple devices. It was developed by Apple Inc. in the
year 2007 to run on the iPhone. It was later advanced to run on other devices such as the
iPad Mini, iPod Touch, Apple TV, and iPad. The interface of iOS is made of controls such
as buttons, sliders, and switches.

The user interface relies on direct manipulation. Users interact with the OS through
tapping, swiping, pinching, and reverse pinching. iOS 8 was developed as a successor to
iOS 7, and it is the eighth version of the operating system. It was released in the year
2014.

It made several improvements on what was provided by iOS 7 in terms of functionality
and user interface. Some of the changes brought about by iOS 8 included an advanced
photos app, notification center, HealthKit, and HomeKit. For instance, with the iOS 8
photo app, users have more editing capabilities for their photos as they can set the
brightness and color to their choice. The photos can also be rotated in either a clockwise or
anti-clockwise direction. These features were not available in iOS 7.

The Notification Center in iOS 8 has only two tabs, that is, the Today and

Notifications tabs. In iOS 7, this had three tabs. Users can now edit the components of
the notification center by the addition of widgets, and replying to messages from the
Notification Center is now possible.

The messaging app has also been improved, since users can now send messages including
videos and audios, as well as set the messages to be deleted after a period of choice. This
shows that iOS 8 has brought with it a number of advancements in iOS. Devices running
iOS 8 have hit the market. iOS 8 apps have also shown a large number of downloads, and
this indicates a positive growth in the future.

Chapter 2:
Getting Started with iOS 8 Swift programming


Swift is the new programming language introduced by Apple to slowly replace ObjectiveC. It offers advanced features which are not available in the Objective-C programming
language. In Swift, programmers can combine Objective-C++, Objective-C, and Swift in
just a single program so as to take advantage of the features from the three languages,
meaning that one can create cool and amazing apps with this language.

Hello World App

Before creating our Hello World app, download the beta version of Xcode 6. You can get
this from the iOS developer center. Once you get through, create a new project by clicking
on:

File->New->New Project. A widow will appear with some options for you to choose.
Select Single view Application.


Give the project a name of choice. Select the language followed by choosing Swift.
Choose a directory to store your project. It will be over and ready to go. Note that in there
Swift programming language, there are no headers and whatever is coded goes to the
.Swift file.

Two template files are also created, that is, ViewController.swift and AppController.swift.
If you run the app at this time, you get an empty view, so wait until we develop some UI
controls. Notice that after you open the Storyboard, the view controller will have a
different size, neither that of the iPad nor the iPhone.

Start by dragging a label, followed by text field, and finally a button. Align them to make
sure that they are in the position that you want.


It is now time to create the outlets. Just start by selecting the Label, hold down the Ctrl
key, and then drag it to the file on the right window. This will form the
ViewController.swift file. Repeat this for three controls so that you can have three outlets.

The three outlets will be as follows:



@IBOutlet var helloLabel : UILabel
@IBOutlet var nameTextField : UITextField
@IBOutlet var helloButton : UIButton

If you are good at programming with Objective-C, you will notice some similarities with
Swift, such the IBOutlet keyword. However, there is a new keyword override. This
keyword will be used in case you override a method in the super class. Swift has brought
about the prevention of common mistakes that programmers make since with this
keyword, overriding methods without realizing it will not be possible.

We then need to declare a method to help in setting up the user interface. This method will
be as follows:

func createUI(){
}

Notice the syntax of declaring a method in Swift. The method has no arguments and it
returns nothing. Our aim is to display a red text at the center of the label written Hello
World. The code below will achieve this:

helloLabel.text = Hello Swift!

helloLabel.textColor = UIColor.redColor()
helloLabel.textAlignment = NSTextAlignment.Center

Notice that we have not used semicolons at the end of the lines, nor the symbol @ before
string literals. Methods for specifying color have also been specified rather than sending
some message to UIcolor. For the purpose of guiding the user, let us add a placeholder to
the text field:

nameTextField.placeholder = Enter your name

To change the text displayed on the button:

helloButton.setTitle(say Hello, forState: .Normal)

Now we are done with creating the user interface. Its time to call the method that we
created earlier on. This can be done as follows:

override func viewDidLoad() {
super.viewDidLoad()
// any additional setup can be done here after loading the view
createUI()
}

We can now run our app. However, let us add some functionality to the button. To do this,
just bring up the assistant editor while in Interface Builder. Drag to the view controller
from the UIButton by pressing the Ctrl key. Name the method as helloAction. This should
be done after moving to action from outlet.


We want to make the label display the text entered in the text field. If nothing was entered
in the text field, an alert dialog should be shown prompting the user to enter some text.
This can be achieved using the code below:

@IBAction func helloAction(sender : AnyObject) {

let nm = nameTextField.text
if nm.isEmpty {
let alertdialog = UIAlertController(title: Error, message: Enter your name,
preferredStyle: UIAlertControllerStyle.Alert)

alertdialog.addAction(UIAlertAction(title: OK, style: UIAlertActionStyle.Default,

handler: nil))

self.presentViewController(alertdialog, animated: true, completion: nil)
} else {

helloLabel.text = Hello \(nm)!
}
}

First, we got the text from the text view and stored it in a constant variable. Constant
variables are highly useful in Swift. We then check whether the constant is empty or
contains some text. If it is empty, we provide an alert box prompting the user to enter his
name.

If it has some text, this name is combined with the word Hello, so the output will be
Hello name, where the name is the text that you entered in the text field. This has really
shed some light to you as far as Swift is concerned.

If you have a little programming experience, the language will be easy for you. Notice
that we have used UIAlertController instead of the UIAlertView. This is because in iOS 8,
the latter can easily crash our app, so we are trying to avoid this.

You can now run the app on an iPhone simulator. Use iPhone 5s. The following will be the
output:


When you enter your name on the text field and press the enter key, you will observe a
change in the red text, since the Swift will change to the name that you have entered.
That is your first app, which is very amazing.

Chapter 3:
Variables and Constants in Swift


You might need to store data for your iOS 8 app. Variables can be used for this purpose. In
Swift, values can be stored either as a variable or as a constant. Example:

var number= 20
let result= 15

The first example illustrates how to store a value as a variable, whereas the second
example illustrates how to store a value as a constant. Note the keywords we have used to
define a constant and a variable.

You have realized that we have not specified the type for our variable and constant in the
above examples. The reason is because Swift has values which are implicitly type stored.
However, you can also choose to specify the type of the value. This is mostly done when
there is no initialization. Swift will infer that since 20 is an integer, the programmer
wanted to store an integer, so the result must also be an integer. To type your values, do
the following:

var number: Double



Let constants must always be initialized. This should be the case even if you have
explicitly typed them. You might want a double after typing an integer value as shown
below:

let value: Double = 30

Instead of storing the value 30, it will store 30.0.
The value of a constant cannot be changed. Trying to do so will result into an error:

let result = 15
result = 22

If you run the program with the above, the following error will be seen:

Error: Cannot assign to let value result

This message means that the value cannot be changed as it is a constant, so dont try this
in Swift.

Chapter 4:
Type Annotations


Sometimes, you are not sure whether the specified value and the expected value match.
This explains the need for type annotation in Swift. This can be applied when we are
declaring variables and functions. The idea behind type annotations in Swift is very easy,
as you just specify the kind of variable that should go into your constants and variables.

Since Swift is safe when it comes to types, you must then adhere to this by making sure
that the type that you assign a variable is the same as the annotated variable. However, do
not be much into this as Swift can do this for you.

Example:
Assuming that you have a variable called studentName and your aim is to pass a string
into this variable, you can do this as follows:

var studentName = John

Swift will automatically know from this that the variable studentName is a string. Let us
try to pass an integer to the same variable:


var studentName = 123

Once we do this, the following error message will be produced:

Type String does not conform to protocol IntegerLiteralConvertable.
This means that Swift will pass an integer value to a variable expected to be a string. So,
in case you get such an error, just know that you have a problem with type annotation.

You might need to specify and create a string type annotation at the beginning of your
program. This can also be done in another file which is to be included as follows:

var studentName: String;

If you assign a string to the variable studentName later on in the code as shown below, all
will be well:

studentName= John

However, trying to assign an integer to this variable as shown below will result into an
error message:

studentName= 123

This shows how type annotations are very useful in Swift, and also very easy to
understand and use in coding.

Chapter 5:
Tuples in Swift


These are one of the features of Swift programming language. With them, one can store
multiple values in a single value. Obviously, these values are closely related to each other.

Example:

var student = (John, 123, true)

Above is an example of a Tuple in Swift. Whenever Swift meets (), it knows that it has
met a Tuple. The values in a Tuple are separated using a comma (,). Just like what happens
in an array, Tuples support the use of indices, whereby the first element is at index 0. To
return the elements of the above Tuple, we can do the following:

student.0 // = John
student.1// = 123
student.3 //= true

Other than the above method, we can assign names to the elements of a Tuple. This is

shown below:

var student = (name: John, admission: 123, isClubMember: true)

After declaring, you can get the values as follows:

student.name // etc

If you want to get a Tuple from a return such as a function, you have to decompose the
parts of the Tuple into variables as follows:

var (name,admission,isClubMember) = student

The variables can then be type put as shown below:

1 Name
2 Admission
3 isClubMember

In case you dont want to assign a value, just put an underscore in the field as shown
below:

var (_, name, _)



Now you know how to use Tuples in Swift. Make use of them when developing iOS 8
apps. They are quite easy to learn and understand, yet very useful in Swift.

Chapter 6:
Enumerations in Swift


If you want to define a common type for a group of items or values which are related, then
enumeration will help you to do so. It supports some of the features which were
traditionally supported by classes only. These features include instance methods and
computed properties. Initial values of members can also be defined by the use of
enumerations.

They have a wide range of uses in Swift programming, and this explains why you need to
understand how to use them. Most programmers view enumerations as complex, but in
real sense, they are not.

Create a new Swift playground. In Swift, they are usually referred to as enum, so dont get
confused when you find this. Let us create an enum that will show the possible ways to
exit from a house:

enum exitDoor {
case Door1
case Door2
case Door3

case Door4
}

The values inside {} (curly braces) are called the member values. To define the member
values in an enum, we use the case keyword. This shows that a new line for defining a
member of the enum has been started. The enum above will contain only the listed above
as members. Other than defining them individually, they can be defined in a single line,
and you separate them with a comma as follows:

enum ExitDoor{
case Door1, Door2, Door3, Door4
}

Notice that the name of every member starts with a capital letter. To use the enumeration
above, we can do as follows:

Var johnExitedThroughDoor= ExitedDoor.Door1

Notice that we declared a variable and assigned a value to the same variable at the same
time. Again, if you were keen on autoComplete, you realized that it gave the options of
only four doors. This is one of the ways used in enums to ensure accuracy.

Apart from the method mentioned above, we can also use this one:


var maryExitedThroughDoor: ExitedDoor
maryExitedThroughDoor= .Door2

It is very clear that from the second method, we have used specification so as to set the
value. Let us demonstrate the use of switch statement to access the values of an enum:

switch johnExitedThroughDoor {
case .Door1:
println(He used Door1)
case .Door2:
println(He used Door2)
case .Door3:
println(He used Door3)
case .Door4:
println(He4 used Door)
}

The output on the playground will show that Door1 was used. Notice we have specified a
case for every member of the enum, as failure to do so will result into an error. You can
delete one of the case statements above and see what will happen. The compiler will tell
that your code has a problem.

Enum Associated Values in Swift



With associated values, extra information can be added to each value of the enum. These
values can be of any type. To demonstrate this, consider the enum shown below:

enum AssociationDemo {
case Name(String)
case Nums(Int, Int, Int)
}

We have defined two case statements, one to hold a string and the other one to hold three
values of type integer. Let us define two variables as shown below:

var name = AssociationDemo.Name(John)
var exampleNums = AssociationDemo.Nums(4, 13, 17)

Let us to check the values using a switch statement:

switch name {
case .Name (let name):
println(The name is \(name))
case .Nums(let val1, let val2, let val3):

println(The value of integer1 is \(val1))


println(The value of integer2 is \(val2))
println(The value of integer3 is \(val3))
}

Now we have accessed the values. We started by accessing the name, and then lastly we
accessed the integers. Every value of the enum has been provided with a case.

Raw Values


With raw values, you are able to declare values inside the enum. It works just in the
opposite way as associated values, since these allow you to declare values outside an
enum. The type of enumeration to use the technique must be specified.

enum Enum2 : String {
case Name = John
case WebSite = http://www.john.com
}
var name = Enum2.Name
var ebsite : Enum2
website = .WebSite

Note the syntax we have used to access the values. Very easy. You should know how to
handle enums without values, as you might try to access empty values.

// Now lets access those values using the handy .Raw()
myName.toRaw() // Outputs Peter
myWebsite.toRaw() // Outputs http://www.peterwitham.com

Chapter 7:
UIAlertView in Swift


An alert view can be represented as follows using iOS 8 SDK and Swift:

var alt = UIAlertController(title: Title of the Alert , message: The message
of the alert, preferredStyle: UIAlertControllerStyle.Alert)
alt.addAction(UIAlertAction(title: OK, style: UIAlertActionStyle.Default,
handler: nil))
self.presentViewController(alt, animated: true, completion: nil)

The style can also be set to either Destructive or Cancel if needed.

Chapter 8:
NSTimer in Swift


Our aim in this chapter is to create a counter application, and it will make use of the Swift
NSTimer class. This class can be used to create a timer in iOS 8 applications. It functions
by waiting for a specific interval of time to elapse so that it can fire.

Once it fires, a message is always to the Swift object which is targeted. A good example is
the scheduling of updates, whereby the timer can be used to trigger this at a specific time.
To create such an app, the project needs to be set up in a specific manner.

Project Setup


Create a new application (Single View) and give it a name of your choice. We then need to
add some elements to the Main.storyboard. These will be obtained from the object Library
in Xcode. These elements include a navigation bar, toolbar, UILabel, Bar Button,Item x 2,
and a flexible Space Bar Button Item.

Adding the Toolbar

Begin by dragging this to the projects bottom:



Click on the Item button and go to the property inspector. Choose play:


The Item will change to a play icon, and the toolbar will be as follows:


Adding the Flexible Space Bar Button Item

The purpose of this is to space out the bar button items. On top of the toolbar located at
the projects bottom part, drag this item:

Item 1 of Bar Button



Drag this to the bottom and left of your toolbar. It should look as follows:


Navigation Bar

On top of the view controller, drag the navigation bar. Avoid overlapping the iPhone
battery by not placing the navigation bar right at the top. Double click the word Title,
and rename it to something else of your choice. In my case, I will rename it to NSTimer
Tutorial so it should look as follows:


Item 2 of Bar Button

Add another bar button on the navigation by dragging it. Place it to the right. Double click
on the Item and change it to Clear.


UILabel

Onto the view controller, drag this item. Place it at the middle of the project. From the
property inspector, edit the label alignment, size, and color (optional). Double click on the
word Label, and change it to 0 (zero).

The interface is now set up. The next thing is to start coding so as to add the necessary
functionality to the timer.

Coding the timer


Select the file ViewController.swift from the navigation area of the project. This is where
coding should be done to add functionality to the NSTimer. To define the timer, we need
to do this between the following lines of code:
class ViewController : UIViewController {
override func viewDidLoad() {

We define our first variable tm for timer which is of type NSTimer as follows:

var tm = NSTimer()

Above the declaration above, we should define the counter and initialize it to 0 as follows:

var counter= 0

At the middle of the storyboard and on the UILabel, press the Ctrl key and drag to your
view controller file. Name it CountingLabel.


Check the ViewController.swift file to see if it has the following code:

@IBOutlet var countingLabel: UILabel!

Repeat the same procedure for the other buttons, but this time, make sure you choose the
connection type Action. After doing that, the following code should be added to your
project:
@IBAction func startButton(sender: AnyObject) { }
@IBAction func pauseButton(sender: AnyObject) { }
@IBAction func clearButton(sender: AnyObject) { }

Values can then be added to the CountingLabel. Note that the UILabel is a string, whereas
the counter is an integer. The output must be converted to a string before adding it to the
label. This can be done as follows:

countingLabel.text = String(counter)

Its time to start the timer. This can be done by adding this functionality to the startButton

as follows:

tm = NSTimer.scheduledTimerWithTimeInterval(TIME_INCREMENT, target:self,
selector: Selector(FUNCTION), userInfo: nil, repeats: BOOL)

Remember that we created variable tm earlier on, and what we done in this case is
assigning a new instance of NSTimer to this. Note that we have added some new things as
explained below:

1. TIME_INCREMENT- specifies the number of seconds after which the timer
fires. We will set this one to 1.
2. FUNCTION- this is a function to be created, and it will be triggered when
the firing time is reached.
3. BOOL- if the value of this is set to YES, it will keep on rescheduling itself
until it is invalidated. After firing, the timer will be invalidated if this value is set to
NO.

The above line of code then becomes:

tm = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector:
Selector(counterUpdator), userInfo: nil, repeats: true)

We have declared a function in the above line of code. We need to create it and use it for
the purpose of incrementing the value of the counter by 1. Assuming that you know the
increment operator, that is, ++, let us use this, and it will increment this value by 1. This
will happen every time this function is called. This will then become:

Func counterUpdator() {
countingLabel.text = String(counter++)
}

You can now run your app. Once you click on start, you will realize how much you have
achieved with less coding.

Stopping the NSTimer


The method Invalidate() is used to pause or stop the NSTimer. We need to add some
functionality to the IBAction of the pause button as shown below:
@IBAction func stopButton(sender: AnyObject) {
tm.invalidate()
}

Now you can play around with the timer by starting it and pausing it.

Clearing the NSTimer


For us to clear the counter, the following needs to be done:

1. Pause the NSTimer from firing.
2. Reset the counter to normal.
3. Clear the countingLabel.

Note that the above order must be adhered to, otherwise the objective will not be achieved.
The following should be the appearance of the IBAction of the clearButton:

@IBAction func clearButton(sender: AnyObject) {
tm.invalidate()
counter = 0
countingLabel.text = String(counter)
}

You can now run your app. Every feature that we wanted has worked, so we are done. The
timer has been created with Swift and NSTimer. This shows how much Swift can be used
to develop amazing apps for iOS 8 devices. More so, using integers and strings should not
be a =n issue to you now as you have learned how to use them.

Chapter 9:
Swift and PHP


It is possible to use Swift to send some post request to a PHP script. This happens on a
server. If you connect your Swift app to a PHP web service, you will achieve
functionalities such as querying the database and even registering the users.

There are also many features that you can enjoy. There exist services that can help you in
achieving this. Programmers without access to a PHP web service or those who cannot
create one for themselves can use these services.

In this section, we will use Parse.com for this purpose. It uses HTTP (Hyper Text Transfer
Protocol) request codes to determine whether the requests that you send succeeded or
failed. These codes are numerous, and each is used for a specific purpose, so you can find
tutorials about these online, and use the right one. We will use the code 200 which tells us
that our connection succeeded, and then we will be able to succeed.

Set up a new Swift project on Xcode 6. Onto the Main.storyboard, drag a button. Link it as
an IBAction to the viewController, and give it a name of your choice. The next thing is to
add functionality to this button. This can be achieved by use of a function. I will call my
function sendFunction. The viewController.Swift should be as follows:


import UIKit
class ViewController: UIViewController {
func sendFunction() {
println(Button Pressed)
}


@IBAction func sendButton(sender: AnyObject) {
sendFunction()
}
override func viewDidLoad() {
super.viewDidLoad()
// add any addition setup after the view is loaded.
}
override func receivedMemWarning() {
super.receivedMemWarning()
//any resources with the ability to be created should be disposed.
}
}
The Button Pressed message will be displayed on the console line area. In case you need
to be emailed when there is a post request, you can use the PHP code below:

$reqVar = $_POST[data];
if (!empty($reqVar)) {

mail(youremail@domain.com,email subject,Post set and Button pressed);


}

If you want to allow someone to access your server, or if you are connecting to a database,
make sure that you are careful so as to avoid malicious attacks.

Posting from Swift to PHP


Declare the following two variables in your function:

var u: NSURL = NSURL(string: http://url.com/path/to/file.php)!
var rqst:NSMutableURLRequest = NSMutableURLRequest(URL:url)

Below the above lines of code, add the following:

var bData = data=something

For you to specify the method that we are sending in, add the following code:

rqst.HTTPMethod = POST

We then need to put together all the above, and send to the server as one. This can be done
as follows:

rqst.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(rqst, queue:
NSOperationQueue.mainQueue())

{
(response, data, error) in
println(response)
}

After running the app at this time, a response will be seen in the console log. It will have
the entire response.

How to Get the Status of the HTTP Code


In the above case, regardless of whether the scripts succeeds or fails, the user will be
directed to the ViewController. We want to direct the user to a new ViewController if the
connection exists and the script runs correctly. An if statement is the right choice here, and
we should combine it with the code 200. This can be done as follows:

if let HTTPResponse = response as? NSHTTPURLResponse {
let sCode = HTTPResponse.statusCode
if sCode == 200 {
// Then do something.
}
}
You can now run your app. You now know how to post to a PHP script from Swift. We
have also used a status code to check whether this went on correctly.

Chapter 10:
Connecting to iTunes Search API


In this chapter, you will know how to connect to the iTunes search API using Swift,
download the JSON results, and parse them to the dictionaries. This information will then
be used to populate the table views. A click event will then be added to the table view for
the sake of user interaction. On clicking this item, the iTunes store will be opened.

How to Connect the User Interface


We should begin by getting a reference to the tableview. In the ViewController.swift just
outside other functions and after class definition, add the following code:

@IBOutlet var appTV : UITableView

The variable appTV will make it possible to connect to the Table View in the storyboard.
Save the file above.

Open the storyboard. Drag from the Table View to the View controller object. This will
link these objects.

How to Make the API Request


Since we have connected the user interface, we can make the API call. Create a new
function, and give it a name of choice. I have called mine iTunesSearch(searchterm:
String). After searching arbitrary terms, this will cause the request to happen. Write the
code below:

func iTunesSearch (term: String) {
// replace spaces with + symbol.
var iTunesTerm = term.stringByReplacingOccurrencesOfString( , withString: +,
options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
// anything that is URL friendly should be escaped
var escapedTerm =
iTunesTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
var path = https://itunes.apple.com/search?term=\(escapedTerm)&media=software
var url: NSURL = NSURL(string: path)
var rqst: NSURLRequest = NSURLRequest(URL: url)
var ctn: NSURLConnection = NSURLConnection(rqst: rqst, delegate: self,
startImmediately: false)
println(URL for searching iTunes API \(url))
ctn.start()
}

We have started by fixing the search term that we pass in. The iTunes search APi

recommends that terms should be of the form first+ second+ third+ words. This
contradicts the form first%20cecond%20. This is why we have used an NSString method,
that is, stringByReplacingOccurencesOfString.

The search term will be modified by replacing all the available spaces with a + symbol.
You can also see the escape, which will make it possible to escape the search term if a
symbol that cannot fit in the URL is found. We have also defined an NSURL, which can
be used in iOS8s network API as a Request URL. The lines below as used above are very
important:

var rqst: NSURLRequest = NSURLRequest(URL: url)
var ctn: NSURLConnection = NSURLConnection(rqst: rqst, delegate: self,
startImmediately: false)

The first line has used the url that we created as the target URL to create an
NSURLRequest object. The second line has done the main job by creating a connection
which is to be used for sending the request. The purpose of setting the delegate to self is to
be able to listen to the information that will come from the connection inside the view
controller class. To begin the request, we have used ctn.start().

How to Prepare for the Response


Now that we have sent the Request, we need to prepare for the response that we will get.
At the end of viewDidLoad, add the following code:

iTunesSearch(JP Software)

JP Software is our search term, so the function will search for any software in the iTunes
store which contains that phrase. You can change the search term to what you want to look
for from the iTunes store. A data object to contain the results is needed for us to get the
results. Let us create an instance of NSMutableData as a class member. Inside the curly
brace and just below the class definition, add the following line of code to achieve this:

var d: NSMutableData = NSMutableData()
var tData: NSArray = NSArray()

Now we are prepared to receive the response. It is time to receive it. Add the following
chunk of code:

func ctn(receivedResponse: NSURLConnection!, receivedResponse response:
NSURLResponse!) {
// clear out the data object if a new request was received.

self.d = NSMutableData()
}
func ctn(ctn: NSURLConnection!, receivedData d: NSData!) {
// add the received data to the data object
self.d.appendData(d)
}
func ctnFinishedLoading(ctn: NSURLConnection!) {
// self.d should hold the resulting info, request is complete
// received data is converted into an object through JSON deserialization
var err: NSError
var jResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(d, options:
NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
if jResult.count>0 && jResult[results].count>0 {
var results: NSArray = jResult[results] as NSArray
self.tData = results
self.appsTableView.reloadData()
}
}

The NSURLconnection receives the response, and then it will call the recivedResponse
method. A new and empty object will be in the line self.d= NSMutableData(). Once the
connection is established, data will be received through the method receivedData(). The
important information here is the argument passed in the method. Every chunk of data is
important, and that is why we have used self.d to append it.

Note that we have used the ctnFinishedLoading() method in the final step. This is after the
connection has been established and all the data has been received. We can then use the
received data in our app. The NSJSONSerialization converts the received data into data
dictionary objects which are useful. This is achieved by deserialization of the results from
iTunes.

The final process involves validating the results so as to check on whether they are what
we expected. The resulting data can then be set to the table data by self.tData object. The
appsTableView reloads its content.

How to Update the Table View UI


Remember that the table view has two functions, a cell function for creation and
modification of cells for each row and a count function whose purpose is to count the
number of rows. We need to put the data we obtained from the web into the table.
Consider the code below:

func tView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return tData.count
}
func tView(tView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) ->
UITableViewCell! {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle,
reuseIdentifier: Cell for Testing)
var rData: NSDictionary = self.tData[indexPath.row] as NSDictionary
cell.text = rData[trackName] as String
// Grabbing the artworkUrl60 key for getting image URL for the thumbnail of the app
var uString: NSString = rData[artworkUrl60] as NSString
var iURL: NSURL = NSURL(string: uString)
// Download representation of the image as NSData at the URL
var iData: NSData = NSData(contentsOfURL: iURL)
cell.image = UIImage(data: iData)
// obtain the formatted price string to be displayed on the subtitle
var fPrice: NSString = rData[fPrice] as NSString

cell.detailTextLabel.text = fPrice
return cell
}

numberOfRowsInSection will return the number of resulting objects from the tableData
member. This is set tothe ctnFinishedLoading method. The row number has been to grab
three values, so we dont return the row number but the three values. These three keys are
then used to construct the title, the subtitle, and the image that will be put along the cell.

The ViewController.swift should look as follows:

import UIKit
class ViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate, NSURLConnectionDelegate, NSURLConnectionDataDelegate {

@IBOutlet var appsTableView : UITableView
var data: NSMutableData = NSMutableData()
var tData: NSArray = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
iTunesSearch(Angry Birds);
}
func iTunesSearch(term: String) {
// replace spaces with + symbol.
var iTunesTerm = term.stringByReplacingOccurrencesOfString( , withString: +,

options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)


// Anything which is not URL-friendly is escaped
var escapedTerm =
iTunesTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
var uPath = https://itunes.apple.com/search?term=\
(escapedTerm)&media=software
var url: NSURL = NSURL(string: uPath)
var rqst: NSURLRequest = NSURLRequest(URL: url)
var ctn: NSURLConnection = NSURLConnection(rqst: rqst, delegate: self,
startImmediately: false)
println(URL for searching iTunes API \(url))
ctn.start()
}
func tView(tView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return tData.count
}
func tView(tView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!)
-> UITableViewCell! {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle,
reuseIdentifier: Cell for Testing)
var rData: NSDictionary = self.tData[indexPath.row] as NSDictionary
cell.text = rData[trackName] as String
// Grabbing the artworkUrl60 key for getting image URL for the thumbnail of the app
var uString: NSString = rData[artworkUrl60] as NSString
var iURL: NSURL = NSURL(string: uString)
// Download representation of the image as NSData at the URL

var iData: NSData = NSData(contentsOfURL: iURL)


cell.image = UIImage(data: iData)
// obtain the formatted price string to be displayed on the subtitle
var fPrice: NSString = rData[fPrice] as NSString
cell.detailTextLabel.text = fPrice
return cell
}
}
func ctn(receivedResponse: NSURLConnection!, receivedResponse response:
NSURLResponse!) {
// clear out the data object if a new request was received.
self.d = NSMutableData()
}
func ctn(ctn: NSURLConnection!, receivedData d: NSData!) {
// add the received data to the data object
self.d.appendData(d)
}
func ctnFinishedLoading(ctn: NSURLConnection!) {
// self.d should hold the resulting info, request is complete
// received data is converted into an object through JSON deserialization
var err: NSError
var jResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(d, options:
NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
if jResult.count>0 && jResult[results].count>0 {
var results: NSArray = jResult[results] as NSArray
self.tData = results

self.appsTableView.reloadData()
}
}
}
}
}

Now the app is ready for running, so do so. Our search term was Angry Birds, so the
following will be obtained as the result:

Chapter 11:
Image Loading and Caching Asynchronously


Our aim is to access images stored in the cache. If they dont exist in the cache, we should
download them while on a background thread. If an image has been downloaded, we
should not download it again, since it will be stored in the cache and hence be accessible
from there. Consider the code below:

func tView(tView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell {
let cell: UITableViewCell = tView.dequeueReusableCellWithIdentifier(kCellIdentifier)
as UITableViewCell
var rData: NSDictionary = self.tData[indexPath.row] as NSDictionary
// making sure that it exists
let cellText: String? = rData[trackName] as? String
cell.textLabel?.text = cellText
cell.imageView?.image = UIImage(named: B52)
// obtain the formatted price string for the subtitle being displayed.
let fPrice: NSString = rData[fPrice] as NSString
let uString = rData[artworkUrl60] as String

// Check the cache for existing key.


let uString = rData[artworkUrl60] as String
// checking the image cache for a key
var img = self.imageCache[uString]
if( img == nil ) {
// download the image if it is not existing
var imgURL: NSURL = NSURL(string: uString)
// Downloading NSData representation of the image
let rqst: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(rqst, queue:
NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,d:
NSData!,error: NSError!) -> Void in
if error == nil {
img = UIImage(data: d)
// Storing the image in the cache
self.imageCache[uString] = img
dispatch_async(dispatch_get_main_queue(), {
if let cToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
cToUpdate.imageView?.image = img
}
})
}

else {
println(Error: \(error.localizedDescription))
}
})
}
else {
dispatch_async(dispatch_get_main_queue(), {
if let cToUpdate = tView.cellForRowAtIndexPath(indexPath) {
cToUpdate.imageView?.image = img
}
})
}
cell.detailTextLabel?.text = fPrice
return cell
}

We have first set the cells placeholder image before downloading the image. Create an
image, and import it to your project just by Ctrl+drag. Name it B52. Set the cells to use
this image. We also checked the image cache for the presence of the image.

The method sendAsynchronousRequest will take a closure/function as a parameter. We
have checked for the presence of an error, and if it doesnt exist, we will create an image

from the data d. The line self.imageCache[uString] = img has the purpose of saving the
image in the image cache, and it will use the image URL as the key. On the UI thread, we
have set the cell image.

You can now run the app, and observe the output. The table view will be very smooth.

Chapter 12:
Using Objective-C classes in Swift


You might need to use of the objective-C classes in Swift. This is possible. Just do the
following:

1. Add .m (Objective-C implementation)
This file, that is, a .m one, should be added to the class and named CustomObject.m
2. Add the Bridging Header
During the addition of the .m file, a dialog will appear which looks as follows:


Just click on Yes.
3. Add .h, the Objective-C Header
Add another .h. Give it the name CustomObject.h

4. Build the Objective-C class


In CustomObject.h, this should be as follows:

#import <Foundation/Foundation.h>
@interface CustomObject : NSObject
@property (strong, nonatomic) id aProperty;
- (void) aMethod;
@end

In CustomObject.m, t should be as follows:

#import CustomObject.h
@implementation CustomObject : NSObject
- (void) aMethod {
NSLog(@aMethod Ran);
}
@end

5. Add a class to the Bridging-Header
This should be:
#import CustomObject.h
6. Use your Object

var iOfObject: CustomObject = CustomObject()


iOfObject.aProperty = Hello World
println(iOfObject.aProperty)
iOfObject.aMethod()

The bridging header is so useful since with it, there is no need to import explicitly. You are
done, so you can safely use the classes.

Chapter 13:
Animations in Swift


With Swift, one can create an app with animations. This can be achieved as follows:

Container View Transitions


If you want to perform an animated transition between views, perform this transition in a
parent container. In the example below, we are going to perform an animated transition
between two UIViews which are colored. The container of the animation will be the third
UIView. Let us start by setting up three views in the viewDidLoad() function:

let cner = UIView()
let rSquare = UIView()// red
let bSquare = UIView() //blue
override func viewDidLoad() {
super.viewDidLoad()
// setting the container frame and adding it to the screen
self.cner.frame = CGRect(x: 60, y: 60, width: 200, height: 200)
self.view.addSubview(cner)
// setting up the red frame
// both the red and blue square frames should be located at the same position
// we then just reuse rSquare.frame
self.rSquare.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
self.bSquare.frame = rSquare.frame
// set background colors

self.rSquare.backgroundColor = UIColor.redColor()
self.bSquare.backgroundColor = UIColor.blueColor()
// let us just add the red square for this time. The blue square will be added later in //the
animation.
self.container.addSubview(self.rSquare)
}
Just run the app. A red square will be the output.
Now to achieve the animation between the two squares, lets create add a @IBAction to
the button in the storyboard:

@IBAction func aButtonTapped(sender: AnyObject) {
// create a pair of more objects and assign them to a single variable (tuple)
let vws = (frontView: self.rSquare, backView: self.bSquare)
// set the style of the transition
let tOptions = UIViewAnimationOptions.TransitionCurlUp
UIView.transitionWithView(self.cner, duration: 1.0, options: tOptions, animations: {
// removing the front object
vws.frontView.removeFromSuperview()
//adding the other object
self.cner.addSubview(vws.backView)
}, completion: { finished in
// once the animation has completed, any code added here will be applied

})
}

After running the app, you will notice that we will get stuck with the blue square. Lets
solve this by adding some logic code which will check the visible square:

// create a pair of more objects and assign them to a single variable (tuple)
var vws : (frontView: UIView, backView: UIView)
// if rSquare has a superView, example, it is in the container,
// set it as front, and bSquare as back
// otherwise, do flip the order
if(self.rSquare.superview){
vws = (frontView: self.rSquare, backView: self.bSquare)
}
else {
vws = (frontView: self.bSquare, backView: self.rSquare)
}
The transition will then be added as follows:
@IBAction func aButtonTapped(sender: AnyObject) {
var vws : (frontView: UIView, backView: UIView)
if(self.rSquare.superview){

vws = (frontView: self.rSquare, backView: self.bSquare)


}
else {
vws = (frontView: self.bSquare, backView: self.rSquare)
}
// setting up the transition style
let tOptions = UIViewAnimationOptions.TransitionCurlUp

UIView.transitionFromView(vws.frontView, toView: vws.backView, duration: 1.0,
options: tOptions, completion: nil)
}

The above will output a unique transition:


The red view will be changed to blue. You can also choose to set the transition to any style
of choice such as:

let tOptions = UIViewAnimationOptions.TransitionFlipFromLeft

Chapter 14:
Creating an Audio Player with Swift


In this chapter, you will learn how to create an audio player with Swift, comprising of a
play button, stop button, and a slider for volume adjustment. We will begin by adding an
audio file to the resources of the project. If you do this, any audio format will be
supported.

Identify an audio file, and drag and drop it in the Supporting files folder of your project. I
have put an mp3 audio called test.mp3 and I have put it in the audiofiles folder of my
project, so do the same.

Creating the User Interface


We want to add the two buttons and the slider. Just select the Main.storyboard and display
the Object Library by View -> Utilities -> Show Object Library. Add the components on
the view window by dragging them from the Library. Modify them to look as follows:


Select the scene view with the storyboard canvas. Get the list of menu options by selecting
the Auto Layout Resolve Auto Layout Issues menu. Select reset. From the view canvas,
select slider. Drag the slider just below the class declaration in the Assistant Editor. Create
an outlet connection and call it vControl in the dialog that will appear. Drag the play
button to below the viewDidLoad(). Establish an action method named pAudio on the
Touch Up inside.

Do the same for the stop button and call the action sAudio. Drag the slider object to the
Assistant Editor panel beneath the created actions. From the dialog, establish a connection
method called adVolume.


Select the ViewController.swift file after closing the Assistant Editor panel, and add the
following to it:

import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
@IBOutlet weak var vControl: UISlider!
var audioPlayer: AVAudioPlayer?

Action Methods


Implement the following methods in the ViewController.swift file:
@IBAction func pAudio (sender: AnyObject) {
if let plyr = audioPlayer {
plyr.play()
}
}

@IBAction func sAudio(sender: AnyObject) {
if let plyr = audioPlayer {
plyr.stop()
}
}

@IBAction func adVolume(sender: AnyObject) {
if audioPlayer != nil {
audioPlayer?.volume = vControl.value
}
}

Creation and Initialization of AVAudioPlayer Object


Add the following code in the viewDidLoad() method of the ViewController.swift file:

override func viewDidLoad() {
super.viewDidLoad()
let u = NSURL.fileURLWithPath(
NSBundle.mainBundle().pathForResource(test,
ofType: mp3)!)
var e: NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: u, e: &error)
if let error = e {
println(audioPlayer error \(error.localizedDescription))
} else {
audioPlayer?.delegate = self
audioPlayer?.prepareToPlay()
}
}

Implementation of the AVAudioPlayerDelegate Protocol Methods


To do this, add the following protocols to the ViewController.swift file:

func audioPlayerDidFinishPlaying(plyr: AVAudioPlayer!, succeeded
flag: Bool) {
}
func audioPlayerDecodeErrorDidOccur(plyr: AVAudioPlayer!,
error: NSError!) {
}
func audioPlayerBeginInterruption(plyr: AVAudioPlayer!) {
}
func audioPlayerEndInterruption(plyr: AVAudioPlayer!) {
}

You can now run your app and play around with the two buttons and the slider.

Conclusion


It can be concluded that iOS 8 is used on Apple devices. Swift is the programming
language developed recently for the purpose of creating iOS 8 apps. iOS 8 is superior
compared to the previous iOS 7 since it offers some better functionalities compared to the
latter. For one to program in Swift, Xcode 6 needs to be set up first, and this is an easy
task.

While programming in Swift, Objective-C classes can be imported to the Swift project.
The vice versa is also true. This language has been used to create amazing apps for
devices running iOS 8 which are now available in the iTunes store. These apps include
cool features such as playing audio, animations, and even loading images asynchronously.

You might also like