Professional Documents
Culture Documents
IOS 8 Programming With Swift A Step by Step Guide Book For Beginners PDF
IOS 8 Programming With Swift A Step by Step Guide Book For Beginners PDF
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
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
Raw Values
Project Setup
Action Methods
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
Definition
Type Annotations
Tuples
Enumerations
UIAlertView
NSTimer in Swift
Animations
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
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
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.
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
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
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
Chapter 2:
Swift is the new programming language introduced by Apple to slowly replace Objective-
C. It offers advanced features which are not available in the Objective-C programming
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.
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.
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
Start by dragging a label, followed by text field, and finally a button. Align them to make
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:
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:
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
Now we are done with creating the user interface. Its time to call the method that we
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.
let nm = nameTextField.text
if nm.isEmpty {
let alertdialog = UIAlertController(title: Error, message: Enter your name,
preferredStyle: UIAlertControllerStyle.Alert)
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
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.
You might need to store data for your iOS 8 app. Variables can be used for this purpose. In
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
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:
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:
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
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:
Swift will automatically know from this that the variable studentName is a string. Let us
try to pass an integer to the same variable:
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:
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:
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
Other than the above method, we can assign names to the elements of a Tuple. This is
shown below:
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:
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
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
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{
Notice that the name of every member starts with a capital letter. To use the enumeration
above, we can do as follows:
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:
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:
case .Door2:
case .Door3:
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
switch name {
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
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.
Chapter 7:
UIAlertView in Swift
An alert view can be represented as follows using iOS 8 SDK and Swift:
handler: nil))
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
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.
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,
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:
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
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
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
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
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:
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:
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.
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:
tm.invalidate()
Now you can play around with the timer by starting it and pausing it.
Clearing the NSTimer
Note that the above order must be adhered to, otherwise the objective will not be achieved.
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:
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
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
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
func sendFunction() {
println(Button Pressed)
}
sendFunction()
super.viewDidLoad()
}
override func receivedMemWarning() {
super.receivedMemWarning()
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,
Posting from Swift to PHP
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())
{
After running the app at this time, a response will be seen in the console log. It will have
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 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:
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
The variable appTV will make it possible to connect to the Table View in the storyboard.
Open the storyboard. Drag from the Table View to the View controller object. This will
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:
var escapedTerm =
iTunesTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
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,
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:
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
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:
Now we are prepared to receive the response. It is time to receive it. Add the following
chunk of code:
NSURLResponse!) {
// clear out the data object if a new request was received.
self.d = NSMutableData()
self.d.appendData(d)
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
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.
return tData.count
UITableViewCell! {
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.
import UIKit
iTunesSearch(Angry Birds);
}
var escapedTerm =
iTunesTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
(escapedTerm)&media=software
startImmediately: false)
return tData.count
// 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)
cell.detailTextLabel.text = fPrice
return cell
NSURLResponse!) {
self.d = NSMutableData()
Now the app is ready for running, so do so. Our search term was Angry Birds, so the
Chapter 11:
Our aim is to access images stored in the cache. If they dont exist in the cache, we should
should not download it again, since it will be stored in the cache and hence be accessible
UITableViewCell {
as UITableViewCell
cell.textLabel?.text = cellText
// obtain the formatted price string for the subtitle being displayed.
NSURLConnection.sendAsynchronousRequest(rqst, queue:
if error == nil {
img = UIImage(data: d)
self.imageCache[uString] = img
dispatch_async(dispatch_get_main_queue(), {
cToUpdate.imageView?.image = img
})
}
else {
println(Error: \(error.localizedDescription))
})
else {
dispatch_async(dispatch_get_main_queue(), {
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.
You can now run the app, and observe the output. The table view will be very smooth.
Chapter 12:
You might need to use of the objective-C classes in Swift. This is possible. Just do the
following:
This file, that is, a .m one, should be added to the class and named CustomObject.m
During the addition of the .m file, a dialog will appear which looks as follows:
#import <Foundation/Foundation.h>
- (void) aMethod;
@end
#import CustomObject.h
@implementation CustomObject : NSObject
- (void) aMethod {
NSLog(@aMethod Ran);
}
@end
#import CustomObject.h
println(iOfObject.aProperty)
iOfObject.aMethod()
The bridging header is so useful since with it, there is no need to import explicitly. You are
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
super.viewDidLoad()
self.view.addSubview(cner)
// both the red and blue square frames should be located at the same position
self.bSquare.frame = rSquare.frame
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)
Now to achieve the animation between the two squares, lets create add a @IBAction to
// create a pair of more objects and assign them to a single variable (tuple)
vws.frontView.removeFromSuperview()
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)
if(self.rSquare.superview){
else {
if(self.rSquare.superview){
vws = (frontView: self.rSquare, backView: self.bSquare)
else {
The red view will be changed to blue. You can also choose to set the transition to any style
Chapter 14:
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
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
Select the ViewController.swift file after closing the Assistant Editor panel, and add the
following to it:
import UIKit
import AVFoundation
Action Methods
plyr.play()
plyr.stop()
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:
super.viewDidLoad()
let u = NSURL.fileURLWithPath(
NSBundle.mainBundle().pathForResource(test,
ofType: mp3)!)
var e: NSError?
if let error = e {
} else {
audioPlayer?.delegate = self
audioPlayer?.prepareToPlay()
Implementation of the AVAudioPlayerDelegate Protocol Methods
flag: Bool) {
error: NSError!) {
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.