Unit - 8 Introduction To IOS Programming
Unit - 8 Introduction To IOS Programming
Originally unveiled in 2007 for the iPhone, iOS has been extended to support other Apple
devices such as the iPod Touch (September 2007) and the iPad (January 2010). As of March
2018, Apple's App Store contains more than 2.1 million iOS applications, 1 million of which
are native for iPads. These mobile apps have collectively been downloaded more than 130
billion times.
The iOS user interface is based upon direct manipulation, using multi-touch gestures.
Interface control elements consist of sliders, switches, and buttons. Interaction with the
OS includes gestures such as swipe, tap, pinch, and reverse pinch, all of which have specific
definitions within the context of the iOS operating system and its multi-touch interface.
Internal accelerometers are used by some applications to respond to shaking the device
(one common result is the undo command) or rotating it in three dimensions (one common
result is switching between portrait and landscape mode). Apple has been significantly
praised for incorporating thorough accessibility functions into iOS, enabling users with
vision and hearing disabilities to properly use its products.
Major versions of iOS are released annually. On all recent iOS devices, iOS regularly checks
on the availability of an update, and if one is available, will prompt the user to permit its
automatic installation. The current version, iOS 13 was released to the public on 19
September 2019, introducing user interface tweaks and a dark mode, along with features
such as a redesigned Reminders app, a swipe keyboard, and an enhanced Photos app. iOS
13 does not support devices with less than 2 GB of RAM, including the iPhone 5s, iPod
Touch (6th generation), and the iPhone 6 and iPhone 6 Plus, which still make up over 10%
of all iOS devices. iOS 13 is exclusively for the iPhone and iPod touch as the iPad variant is
now called iPadOS.
iOS programming is a set of processes and procedures involved in writing software for
iPhone developed by Apple Inc.
iOS Platform
The iOS SDK (Software Development Kit) allows for the development of mobile apps on
iOS. While originally developing iPhone prior to its unveiling in 2007, Apple's then-CEO
Steve Jobs did not intend to let third-party developers build native apps for iOS, instead
directing them to make web applications for the Safari web browser. However, backlash
from developers prompted the company to reconsider with Jobs announcing in October
1
2007 that Apple would have a software development kit available for developers by
February 2008. The SDK was released on March 6, 2008.
The SDK is a free download for users of Mac personal computers. It is not available for
Microsoft Windows PCs. The SDK contains sets giving developers access to various
functions and services of iOS devices, such as hardware and software attributes. It also
contains an iPhone simulator to mimic the look and feel of the device on the computer
while developing. New versions of the SDK accompany new versions of iOS. In order to test
applications, get technical support, and distribute apps through App Store, developers are
required to subscribe to the Apple Developer Program.
Combined with Xcode, the iOS SDK helps developers write iOS apps using officially
supported programming languages, including Swift and Objective-C. Other companies have
also created tools that allow for the development of native iOS apps using their respective
programming languages.
Environment Setup
For development of iOS applications, we need to install Xcode editor, its apple integrated
development environment (IDE). The Xcode editor is the primary development tool for any
type of apple platforms like OSX Software’s, iPhones App, Mac, etc.
The requirement of the Xcode editor is that we should have minimum Apple Laptop or Mac
Computer for development of iOS application. We can download Xcode editor from Apple
website or Apple app store and this editor is completely free we don’t need to pay
anything for Apple.
2
Creating an Xcode Project
With Xcode installed, it is time to launch it for the first time. If all went well, you should see
the Welcome to Xcode window, which contains a few useful links and helps you create a
new application. To create your first iOS application, select Create a new Xcode
project from the list of options.
Xcode makes it easy to create a new Xcode project by offering a handful of useful project
templates. The Single View Application template is a good choice for your first application.
Select it from the list of iOS > Application templates and click Next.
3
Figure 8-2: Creating a Project
The next window lets you configure your Xcode project. Fill in the fields as shown in the
screenshot below and click Next.
4
Figure 8-3: Configuring a new Project
Once we click on Next button new dialog will open in that we need to select the location
to save our project. Once you select the location to save project then click on Create button
like as shown below.
5
Figure 8-4: Selecting project location
After click on Create button the Xcode will create and open a new project. By default, our
project structure will be like as shown below.
6
Building the Interface
In our project Main.storyboard and ViewController.swift are the main files which we used
to design app user interface and to maintain source code.
• Main.storyboard - Its visual interface editor and we will use this file to design our
app user interface
• ViewController.swift - It contains source code of our application and we use this
file to write any code related to our app.
Now in project select Main.storyboard file the Xcode will open visual interface editor like
as shown below.
Now select ViewController.swift file in your project that view will be like as shown below.
7
Figure 8-7: First look of ViewController.swift
Now we will add controls to our application for that open Object Library. The Object Library
will appear at the bottom of Xcode in right side. In case if you don't find Object library, click
on the button which is at the third position from the left in the library selector bar like as
shown below. (Alternatively you can choose View -> Utilities -> Show Object Library).
8
Figure 8-9: Adding label to the project
Now we will change the text of label for that click on label in right side the label properties
will open in Text property textbox write the “Hello World”. Once we change the label text
now we will change the position of label control for that select label control -> Click
on label control and just drag the label control like as shown below.
9
Once we click and drag the label control we can able to see multiple properties like
“Center Horizontally in Container”, “Center Vertically in Container”, etc.
We will set “Center Horizontally in Container”, “Center Vertically in Container” properties
for label control to make our label appeared in centered position. Once we set these two
properties we can able to see two lines which appear like cross on our hello world label like
as shown below.
10
Once we select the required simulator then we will run our application by
using Run button, located in the top-left corner of the Xcode toolbar like as shown below.
Once we run the iOS hello world application we will get output like as shown below.
Making Connections
A connection lets one object know where another object is in memory so that the two
objects can communicate. There are two kinds of connections that you can make in
Interface Builder: outlets and actions. An outlet is a reference to an object. An action is a
method that gets triggered by a button or some other view that the user can interact with,
like a slider or a picker.
For making connections you have to use iOS Outlets and Actions. In iOS Outlets and Actions
are basically the property symbol of IBoutlets and IBActions where IB called Interface
Builder. Outlet is basically the reference object and action is the method which is used to
perform some type of actions.
Following is the syntax of using iOS Actions and Outlets in applications.
If you observe above syntax we used “@IBOutlet” to add reference of label control and
we used “@IBAction” to add button click action to change label control text.
11
To demonstrate connection, let’s take an example of an iOS application containing two
view controls (one label control and another button control). While clicking on the button
control we must be able to change text of label.
So, let’s begin by adding label and button controls in our storyboard.
Now we will map our controls to ViewController.swift file for that we need to
use Assistant editor in Xcode. Open the Xcode editor in assistant mode for that click on
the overlap circle button in Xcode toolbar at top right side like as shown below.
Now press Ctrl button in keyboard and drag the controls from your canvas to the code
display in ViewController.swift file like as shown below.
12
Figure 8-17: Connecting UI controls to application code
Once you drag the controls from viewcontroller to code in ViewController.swift file now
write code in @IBAction to change the label text when click on button. Once we make
required changes our ViewController.swift file should be like as shown below.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var labeltxt: UILabel!
@IBAction func buttonaction(sender: AnyObject) {
labeltxt.text = "We love BCA "
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Once we run application click on button it will change the label text. The button performs
the action for label to change its outlet text.
13
Figure 8-18: Output demonstrating connection
Swift maintains the expressiveness of Objective-C while introducing a syntax that is safer,
succinct, and readable. It emphasizes type safety and adds advanced features such as
optionals, generics, and sophisticated structures and enumerations. Most importantly,
Swift allows the use of these new features while relying on the same tested, elegant iOS
frameworks that developers have built upon for years.
Types in Swift
Swift types can be arranged into three basic groups: structures, classes, and enumerations.
All three can have:
• properties – values associated with a type
• initializers – code that initializes an instance of a type
• instance methods – functions specific to a type that can be called on an instance of
that type
• class or static methods – functions specific to a type that can be called on the type
itself
14
c
Variables
You must declare them using var keyword as follows –
var variableName = <initial value>
You can provide a type annotation when you declare a variable, to be clear about the kind
of values the variable can store. Here is the syntax –
var variableName:<data type> = <optional initial value>
var varA = 42
print(varA)
var varB:Float
varB = 3.14159
print(varB)
When we run the above program using playground, we get the following result −
42
3.1415901184082
Optionals
Swift also introduces Optionals type, which handles the absence of a value. Optionals say
either "there is a value, and it equals x" or "there isn't a value at all".
15
Here’s an optional Integer declaration –
var perhapsInt: Int?
The above declaration is equivalent to explicitly initializing it to nil which means no value –
var perhapsStr: String? = nil
if myString != nil {
print(myString)
} else {
print("myString has nil value")
}
When we run the above program using playground, we get the following result –
myString has nil value
Constants
Constants refer to fixed values that a program may not alter during its execution. Constants
can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are enumeration constants as well.
Constants are treated just like regular variables except the fact that their values cannot be
modified after their definition.
Before you use constants, you must declare them using let keyword as follows –
let constantName = <initial value>
When we run the above program using playground, we get the following result –
42
Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. Swift is rich in built-in operators and provides the following types of
operators −
• Arithmetic Operators
• Comparison Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Range Operators
16
• Misc Operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by Swift language.
Assume variable A holds 10 and variable B holds 20, then −
Comparison Operators
The following table shows all the relational operators supported by Swift language. Assume
variable A holds 10 and variable B holds 20, then –
Logical Operators
The following table shows all the logical operators supported by Swift language. Assume
variable A holds 1 and variable B holds 0, then –
17
! Called Logical NOT Operator. Use to reverses the logical !(A && B) is true.
state of its operand. If a condition is true, then the Logical
NOT operator will make it false.
Bitwise Operators
Bitwise operators work on bits and perform bit by bit operation. The truth tables for &, |,
and ^ are as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
Bitwise operators supported by Swift language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then 7−
18
>> Binary Right Shift Operator. The left operands value is A >> 2 will give 15, which
moved right by the number of bits specified by the is 0000 1111
right operand.
Assignment Operators
Swift supports the following assignment operators –
Range Operators
Swift includes two range operators, which are shortcuts for expressing a range of values.
The following table explains these two operators.
19
…2 gives beginning… to
1,2
Misc Operators
Swift supports a few other important operators including range and ? : which are explained
in the following table.
Decision Making
Swift provides the following types of decision making statements.
print("Value of
variable varA is
\(varA)");
Output:
varA is less than 20
Value of variable varA
is 10
20
/* If condition is
true then print the
following */
print("varA is less
than 20");
} else {
/* If condition is
false then print the
following */
print("varA is not
less than 20");
}
print("Value of
variable varA is
\(varA)");
Output:
varA is not less than
20
Value of variable varA
is 100
} else if varA == 50 {
/* If condition is
true then print the
following */
print("varA is equal
to than 50");
} else {
/* If condition is
false then print the
following */
print("None of the
values is matching");
}
21
print("Value of
variable varA is
\(varA)");
Output:
None of the values is
matching
Value of variable varA
is 100
if varB == 200 {
/* If condition
is true then print the
following */
print("Second
condition is also
satisfied");
}
}
print("Value of
variable varA is
\(varA)");
print("Value of
variable varB is
\(varB)");
Output:
First condition is
satisfied
Second condition is
also satisfied
Value of variable varA
is 100
Value of variable varB
is 200
22
5 switch statement A switch statement var index = 10
allows a variable to be switch index {
tested for equality case 100 :
against a list of values. print( "Value of
index is 100")
case 10,15 :
print( "Value of
index is either 10 or
15")
case 5 :
print( "Value of
index is 5")
default :
print( "default
case")
}
Output:
Value of index is
either 10 or 15
Loops
Swift programming language provides the following kinds of loop to handle looping
requirements.
Output:
Value of index is 10
Value of index is 20
Value of index is 30
Output:
Value of index is 10
Value of index is 11
23
Value of index is 12
Value of index is 13
Value of index is 14
Output:
Value of index is 10
Value of index is 11
Value of index is 12
Value of index is 13
Value of index is 14
Arrays
You can create an empty array of a certain type using the following initializer syntax –
var someArray = [SomeType]()
You can use the following statement to create an empty array of Int type having 3 elements
and the initial value as zero –
var someInts = [Int](count: 3, repeatedValue: 0)
Following is one more example to create an array of three elements and assign three values
to that array –
var someInts:[Int] = [10, 20, 30]
You can retrieve a value from an array by using subscript syntax, passing the index of the
value you want to retrieve within square brackets immediately after the name of the array
as follows –
var someVar = someArray[index]
The following example shows how to create, initialize, and access arrays –
var someInts = [Int](count: 3, repeatedValue: 10)
Output:
Value of first element is 10
Value of second element is 10
Value of third element is 10
24
Strings
You can create a String either by using a string literal or creating an instance of a String
class as follows –
// String creation using String literal
var stringA = "Hello, Swift!"
print( stringA )
Empty String
You can create an empty String either by using an empty string literal or creating an
instance of String class as shown below. You can also check whether a string is empty or
not using the Boolean property isEmpty.
if stringA.isEmpty {
print( "stringA is empty" )
} else {
print( "stringA is not empty" )
}
if stringB.isEmpty {
print( "stringB is empty" )
} else {
print( "stringB is not empty" )
}
Output:
stringA is empty
stringB is empty
String Concatenation
You can use the + operator to concatenate two strings or a string and a character, or two
characters. Here is a simple example –
let constA = "Hello,"
let constB = "World!"
Output:
Hello,World!
25
String Length
Swift strings do not have a length property, but you can use the global count() function to
count the number of characters in a string. Here is a simple example –
Output:
Hello, Swift 4!, length is 15
String Comparison
You can use the == operator to compare two strings variables or constants. Here is a simple
example –
var varA = "Hello, Swift!"
var varB = "Hello, World!"
if varA == varB {
print( "\(varA) and \(varB) are equal" )
} else {
print( "\(varA) and \(varB) are not equal" )
}
Output:
Hello, Swift! and Hello, World! are not equal
Function
A function's arguments must always be provided in the same order as the function's
parameter list and the return values are followed by →.
Take a look at the following code. The student’s name is declared as string datatype
declared inside the function 'student' and when the function is called, it will return
student’s name.
26
When we run the above program using playground, we get the following result –
First Program
About Functions
When we run above program using playground, we get the following result –
40
45
120
When we run the above program using playground, we get the following result −
Alice
The view hierarchy is a major part of the responder chain, and it is something that the
application frameworks use to determine the layering order of views when they render the
content of a window in a drawing pass. The view hierarchy is also the governing concept
behind view composition: You construct compound views by adding sub views to a super
view. Finally, the view hierarchy is a critical factor in the multiple coordinate systems found
in a window.
27
Figure 8-20. View Hierarchy in iOS
A view is related to other views through two properties, and these relationships determine
the form of the hierarchy:
• super view — The view above a given view in the hierarchy; this is the view that
encloses it. All views except the topmost view must have a super view.
• sub views — The views below a given view in the hierarchy; these are the views
that it encloses. A view may have any number of sub views, or it may have none.
28
Figure 8-21. Example of View Hierarchy in iOS
29
To demonstrate storyboard now I am going to create a storyboard containing a Tab and
multiple view controllers linking with the Tab.
So, let’s begin by creating a project with following information:
§ Product Name: MyExample.
§ Organization Name: Fill this in however you like.
§ Organization Identifier: The identifier you use for your apps.
§ Language: Swift.
§ User Interface: Storyboard.
§ Make sure you’ve unchecked the Use Core Data, Include Unit Tests and UI
Tests options.
Open Main.storyboard in the Project navigator to view it in the Interface Builder editor:
Here, you see a single view controller containing an empty view. The arrow pointing to the
view controller from the left indicates it’s the initial view controller for this
storyboard. Xcode enables Auto Layout and Size Classes by default for storyboards. They
allow you to make flexible user interfaces that can resize easily, which is useful for
supporting various sizes of iPhones and iPads.
30
Figure 8-24. Adding Tab Controller to Main. Storyboard
The arrows between the tab bar controller and the view controllers it contains represent
the container relationship. The icon shown below, in the middle of the arrow body,
signifies that they have an embed relationship.
31
Build and run and you’ll see something like this in the console:
This error simply indicates that the app didn’t find the initial view controller to show.
To fix this error, Open Main.storyboard and select the Tab Bar Controller Scene. On the
right, select the Attribute inspector.
Checking this box will identify the selected view controller as the initial entry point for the
storyboard you’re on. Also, an arrow will appear on the left of the view controller.
Now, build and run and you’ll see an empty view controller with a tab bar that has two
items at the bottom.
32
Figure 8-26. Output demonstrating Tab View Controller
33
We can apply custom styles to the content in iOS label
control like changing the font style, font size, adding
background colors, etc. based on our requirements.
3 iOS UI Text Fields In iOS Text fields are used to allow users to enter single
line of text as an input to an app. The text fields
automatically bring up a keyboard to enter a text
whenever the user touch or taped it and these text fields
are helpful to gather small amounts of text from the user
like name, email, etc. By using text fields, we can perform
some actions like search operation, based on that text.
We can use Text Fields in our iOS application by
adding UITextField class reference in our applications.
4 iOS UI Image View In iOS, image view is used to show the images in iOS
application and it will resize the images automatically to
make fit with the current size of view.
By using iOS image view, we can show single image or
animated sequence of images with transparent or opaque
background based on our requirement.
5 iOS Progress Bar In iOS progress indicators or progress bars are used to
(Progress View) show the progress of task in application instead of making
people staring at a static screen while performing lengthy
data operations.
By using iOS progress indicators or bars we can make the
people to understand that how long the process will take
to finish the task like as shown below:
34
By using iOS switches we can implement features like
allowing users to turn the settings on or off based on
their requirements.
The visual representation of iOS switches with on and off
options will be like as shown below:
11 iOS UI Scroll View In iOS, scroll view is used to show the content which is
larger than the scroll view boundaries like viewing larger
content in documents, showing multiple images in app. In
our iOS application whenever we see the scroll view it is
indication that there is extra content other than visible
area.
We can use Scroll View in our iOS applications by
adding UIScrollView class reference.
35
Creating a Simple iOS Application
Here we going to create a simple application to show the addition of two numbers. Our
application contains two Text Fields for inputting two numbers and a Button to trigger click
event. Also I will create a Label for displaying the result.
import UIKit
class ViewController: UIViewController {
36
}
Exercise
37