• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

ios

Class and Struct in Swift

May 10, 2015 By Ravi Shankar 3 Comments

Download the playground file from github (Classes and Struct)

Class

A class is a blue print for a real-word entity such Player, Person etc. and it is used for creating objects. Class can have properties to store values and methods to add behaviour. Let us see this with an example class called Rectangle which has some properties and two methods for calculating area and for drawing a rectangle.

[code language=”swift”]class Rectangle {

var name:String = ””
var length:Double = 0
var breadth:Double = 0

func area() -> Double {
return length * breadth
}

func draw() -> String {
return “Draw rectangle with area \(area()) “
}
}

let rect = Rectangle()

rect.length = 20
rect.breadth = 10
rect.draw()
[/code]

 

In the above example, we have a class named Rectangle, with name, length and breadth as properties, area and draw are functions. rect is a instance variable or object of Rectangle class. On setting the length and breadth and calling draw function should provide the following output in Playground.

201505101309.jpg

Similarly the below code create a Square class

[code language=”swift”]class Square {

var name:String = ””
var length:Double = 0

func area() -> Double {
return length * length
}

func draw() -> String {
return “Draw a square with area \(area()) “
}
}

let squr = Square()
squr.length = 20
squr.draw()
[/code]

 

Now instead of repeating property and functions in each classes let us use class inheritance to simplify these classes.

Class Inheritance

Let us create a parent class called Shape and its properties and functions will be inherited by Sub Classes Rectangle and Square.

Parent Class – Shape

[code language=”swift”]class Shape {
var name: String = ””

func area() -> Double {
return 0
}

func draw() -> String {
return “Draw a \(name) with area \(area()) “
}
}
[/code]

 

Sub Class – Square

[code language=”swift”]class Square:Shape {

var length: Double = 0
override func area() -> Double {
return length * length
}
}

let squr = Square()
squr.name = “My Square”
squr.length = 5
squr.draw()
[/code]

 

Sub Class – Rectangle

[code language=”swift”]class Rectangle:Shape {
var length: Double = 0
var breadth: Double = 0

override func area() -> Double {
return length * breadth
}
}

let rect = Rectangle()
rect.name = “My Rectangle”
rect.length = 5
rect.breadth = 10
rect.draw()
[/code]

 

Parent class Shape has been created with name property and functions area and draw. The child class Square and Rectangle will inherit these property and methods. Apart from the parent class property, Square can have its own property length and Rectangle has length and breadth. The parent class area function has been overridden by Square and Rectangle class to calculate corresponding areas. Now if you want add one more Shape such as Triangle, Circle etc the new class has to inherit Parent class (Shape) and add its own property and methods (or override methods).

Initialisers

Initialisers in Class and Struct are used for setting the default values for properties and for doing some initial setup. Here is a typical example of initialiser in a Class where the name property is initialised at the time of creating an instance.

[code language=”swift”]class Shape {

var name: String
init(name: String) {
self.name = name
}

func area() -> Double {
return 0
}

func draw() -> String {
return “Draw a \(name) with area \(area()) “
}
}

class Square: Shape {
var length: Double = 0

init() {
super.init(name: “MySquare”)
}

override func area() -> Double {
return length * length
}

override func draw() -> String {
return “Draw a \(name) with area \(area()) “
}
}

let squr = Square()
squr.length = 10
squr.draw()
[/code]

 

The sub class Square initialises the name property in init function by calling super.init and after creating the Square instance you need to pass value for the length property.

Designated and Convenience Initialisers

Initialiser which initialises all the properties in a class is known as designated initialiser. A convenience initialiser will initialise only selected properties and in turn will call the designated initialiser in init function. Listed below is a Square class with designated initialiser and convenience initialiser

[code language=”swift”]class Shape {
var name: String
init(name: String) {
self.name = name
}

func area() -> Double {
return 0
}

func draw() -> String {
return “Draw a \(name) with area \(area()) “
}
}

class Square: Shape {
var length: Double

// Designated Initializer
init(length:Double, name:String) {
self.length = length
super.init(name: name)
}

// Convenience Initializer
convenience init(length: Double) {
self.init(length:length, name:“MySquare”)
}

override func area() -> Double {
return length * length
}

override func draw() -> String {
return “Draw a \(name) with area \(area()) “
}
}

let squr = Square(length: 10,name: “MySquare”)
squr.draw()

let squrNew = Square(length: 20)
squrNew.draw()[/code]

Computed Property

A property in swift can be used for performing operation at the time of assigning value. Here is an example, where the length of Square is computed based on assigned area.

[code language=”swift”]class Sqaure {
var length: Double = 0
var area: Double {
get {
return length * length
}

set (newArea) {
self.length = sqrt(newArea)
}
}
}

let square = Sqaure()
square.area = 4 // set call
square.length = 6
square.area // get call[/code]

lazy Property

Swift also provides lazy property whose value is assigned when the user access the property.

[code language=”swift”]class Person {
var name: String
init (name: String) {
self.name = name
}

lazy var message: String = self.getMessage()

func getMessage() -> String {
return “Hello \(name)”
}
}

let person = Person(name: “Jason”)
person.message[/code]

in the above code example, the value for message property is not set at the initialisation and will be set only when call the message property in person object. Some typical where you could due lazy property is when retrieving values from performance intensify operation such as Network or Read/Write.

Property Observers

Swift provides two property observers, willSet and didSet. These methods gets triggered when a value is about to be set for a property or after setting the property.

[code language=”swift”]class Square {
var length: Double = 0 {
willSet(newLength) {
println("Setting length \(self.length) to new length \(newLength)")
}

didSet {
println(“Length is modified – do some action here”)
}
}

var area: Double {
get {
return length * length
}

set (newArea) {
self.length = sqrt(newArea)
}
}
}

let square = Square()
square.length = -6
square.area
[/code]

 

In the above example, Square class length property has a willSet and didSet observers.

Struct

Struct and Class can both have properties, methods, protocols, extensions and initialisers. You can use struct to hold simple values and when you want to pass around those across your program. A typical example would be using Struct to hold values from a web service call. Listed below is a web service call that we had seen earlier in Xcode and Playground overview. In the below code example you should find a GeoDetails struct for storing the values returned from geoip web service.

[code language=”swift”]struct GeoDetails {
var country: String
var ip: String
var isp: String
var latitude: Double
var longitude: Double
var timeZone: String

init(country: String, ip: String, isp: String, latitude:Double, longitude:Double, timeZone:String) {
self.country = country
self.ip = ip
self.isp = isp
self.latitude = latitude
self.longitude = longitude
self.timeZone = timeZone
}

func description() -> String {
return “Country ” + self.country + “, ip ” + self.ip + “, isp ” + self.isp + “, latitude \(self.latitude), longitude \(self.longitude) “
}
}

var geoDetails: GeoDetails?
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)

let url = NSURL(string: “http://www.telize.com/geoip”)

NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if error == nil {
var error:NSError?
if let result = data {
if let dict = NSJSONSerialization.JSONObjectWithData(result, options: NSJSONReadingOptions.AllowFragments, error: &error) as? NSDictionary {
geoDetails = GeoDetails(country: dict[“country”] as! String, ip: dict[“ip”] as! String, isp: dict[“isp”] as! String, latitude: dict[“latitude”] as! Double, longitude: dict[“longitude”] as! Double, timeZone: dict[“timezone”] as! String)
println(geoDetails?.description())
} else {
println("Error")
}
}[/code]

Download the playground file from github (Classes and Struct)

Filed Under: Apple, ios, Programming Tagged With: Apple, Classes, Structures, Swift

Swift – Beginners Tutorial

May 8, 2015 By Ravi Shankar Leave a Comment

Swift is the latest programming language released by Apple for developing OS X and iOS apps.

  • Best of C and Objective-C
  • Adopts safe programming patterns and modern features
  • Supports Playground, a tool for seeing the result immediately.
  • Provides access to Cocoa libraries and can work in conjunction with Objective-C
  • Combines Procedural and Object-Oriented programming.
  • No need to use semicolon at the end of statement. Use it only when you have more than one statement in single line.
  • Swift uses var and let. only mutable variable needs var.
  • Swift uses type inference.
  • Supports unicode characters. You can use any character as variable.
  • Prefer usage of constant (let) for immutable than using var.
  • Optional variables can contain value or nil. – var givenName : String? = “Ravi”
  • Swift’s Switch supports all kinds of datatype and operations and does not need a break statement after each case statement.
  • No need to enclose your expression in brackets with if statements
  • Swift function supports default value for the parameter and variable parameter.
  • Closures are like blocks in Objective-C ( ) -> ( )
  • No need to specify header file in Swift
  • No need to specify base class and there is no universal base class
  • No difference between instance variable and properties
  • Tuples – Grouping of multiple values.
  • Nested multiline comments are allowed.
  • Use typealias to provide different name to an existing type.
  • Swift nil represents absence of value and objective – C nil represents pointer to a non-existent object.
  • Implicitly unwrapped optional let pincode : String! = “E151EH”
  • Provides Assertion to end code execution where certain criteria is not met.
  • Swift’s String is value type and not passed by reference.
  • Supports Optional Binding and Optional Chaining

Variables and Constants

[code language=”swift”]
// Variables and Constants

var myStr = "Swift"
var myValue = 23.1 //(Implicit variable declaration or type inference)
var myDoubleValue: Double = 23 //(Explicit variable declaration)

// let

let myAge = 38
let message = "My age is " + String(myAge) //(Converting value to a String)
let newMessage = "My age is \(myAge)" //(Converting value to a String using backslash or interpolation)

[/code]

Data types in Swift

  • String
  • Int (Range -2,147,483,648 to 2,147,483,648)
  • Double (15 digit precision)
  • Float (6 digit precision)
  • Bool

Fun with String

[code language=”swift”]// String
var movie:String = "Independence Day "
count(movie) // count of string

// Use NSString to format a double or float value
var range = NSString(format: "%.2f", 24.5)

// Concatenate String values
movie += String(range)[/code]

 

Collection Types

Array

[code language=”swift”]// Declarations
// var fruits = ["Orange", "Apple", "Grapes"] – Short declartion
// var fruits:Array = ["Orange", "Apple", "Grapes"] – Long declaration
// var fruits:[String] = [] – Assign empty array

var fruits:[String] = ["Orange", "Apple", "Grapes"] // short declaration with type.

// insert item at index
fruits.insert("Mangoes", atIndex: 2)

// append item to the last
fruits.append("Pine Apple")

// count of array
fruits.count

// remove item
fruits.removeAtIndex(1)

// sort array elements
fruits.sort { (a, b) -> Bool in
a < b
}

// retrieve index using find
find(fruits, "Mangoes")
[/code]

Dictionary

[code language=”swift”]// Dicionary

// Declaration

// var employees = [1:"John",2:"Peter",3:"David"] // Short form

// var employees:Dictionary = [1:"John",2:"Peter",3:"David"] // Long form

// var employees:[Int:String] = Dictionary() // Empty dictionary

var employees:[Int:String] = [1:"John",2:"Peter",3:"David"] //Short form with type

// Add new item to dictionary

employees[4] = "Bob"

// Remove an item using key

employees.removeValueForKey(3)
[/code]

Assignment Operator

  • a = b
  • let (a,b) = (2,3) – supports tuple.
  • Does not return value.

Arithmetic Operators

  • Addition (+), Subtraction (-), Multiplication (*), Division (/)
  • + can be used for string concatenation.
  • % – Returns remainder for both +ve and -ve numbers. Also returns remainder for floating point numbers.
  • Increment and Decrement operators, ++i (i = i + 1), —i (i = i – 1).
  • Supports i++ and i— (increments or decrements after returning the value).
  • Unary Minus and Unary Plus

Compound AssignmentOperator

  • x += 2 is same as x = x + 2.

ComparisonOperators

  • x == y
  • x != y
  • x > y
  • x < y
  • x >= y
  • x <= y
  • === and !== used for testing object references.

Ternary Conditional Operator

  • a = flag ? 10 : 20 (if flag is true then a will updated to 10 and 20 incase it is false).

RangeOperators

  • Closed Range – e.g.:- 1…10, has three dots and includes values from 1 to 10.
  • Half Closed – e.g.:- 1..10, has two dots and includes values from 1 to 9

LogicalOperators

  • NOT ( !x )
  • AND ( x && y )
  • OR ( x || y )

Control Flow

[code language=”swift”]// Control flow

// if else
if fruits[0] == "Grapes" {
println("for breakfast")
} else if fruits[0] == "Apple" {
println("for lunch")
} else {
println("Nothing")
}

// for statements
// exclusive range

for index in 0..<h3><u>Comments</u></h3>[code language="swift"] Single line comments // examples
Multiline comments /* example1
example2 */

[/code]

Function

[code language=”swift”]func sum(number1:Int, number2: Int) -&gt; (Int) {
return number1 + number2
}[/code]

The above function is an example of multiple input parameters. It does the addition of two numbers where number1 and number are arguments of type Int and it returns a value of type int. And a function without parameter looks like this.

[code language=”swift”]
func sum() -&gt; (Int) {
return 10 + 5
}[/code]

The above function is an example of multiple input parameters. It does the addition of two numbers. number1 and number are arguments of type Int and it returns a value of type int. And a function without parameter looks like this. Swift function can also have multiple return values.


Define external parameter name

[code language=”swift”]func sum(addNumber1 number1:Int, withNumber2 number2: Int) -&gt; (Int) {
return number1 + number2
}

println(sum(addNumber1: 10, withNumber2: 20))
[/code]

 

addNumber1 and withNumber are external parameter names for two parameters. And you use # to tell local and external parameter name are same.

[code language=”swift”]
func sum(#number1:Int, #withNumber2: Int) -&gt; (Int) {
return number1 + withNumber2
}
println(sum(number1: 10, withNumber2: 20))[/code]

Function with default parameter value

[code language=”swift”]func sum(number1:Int, withNumber2: Int = 20) -&gt; (Int) {
return number1 + withNumber2
}
println(sum(10))[/code]

The above function has default value for the second parameter.

Variadic Parameters

 

A function with variadic parameters can accept zero or more values. Maximum of one parameter is allowed in a function and it is always last in the list.

[code language=”swift”]
// Variadic parameters
func totalSum(numbers:Int…) -&gt; Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
totalSum(1,2,3,4,5)[/code]

Variable and inout parameters

Variable parameters in a function are indicated by var keyword and the scope is available only within the function. If you want to access the modified variable value outside the function then you specify them as inout parameter. And prefix with & while passing the parameter in the function call.

[code language=”swift”]
// inout parameters
var employee = "Ravi"

func greetings(inout employee:String) {
employee += "!"
}
println(greetings(&amp;employee))
println(&amp;employee)[/code]

Filed Under: Apple, ios, Mac Tagged With: Apple, Quick Reference, Swift

Optional binding and Optional Chaining

May 7, 2015 By Ravi Shankar 6 Comments

Swift has a feature that lets users to assign optional value to a variable or a constant. Optional variable or constant can contain a value or a nil value. Let us take the following example which tries to find a given string in a array of string.

Optional Binding

[code language=”swift”]var fruits = ["Apple","Orange","Grape","Mango"]
let searchIndex = find(fruits, "Apple”)[/code]

The searchIndex would return value if the fruit exists or nil value if it doesn’t exist.

[code language=”swift”]println("Fruit index is \(searchIndex)”)
[/code]

 

The proper way to handle this by using Optional binding method.

[code language=”swift”]if let searchIndex = searchIndex {
println("Fruit index is \(searchIndex)")
} else {
println("Not available")
}[/code]

This would ensure only when searchIndex has a value the println with searchIndex gets executed.

Optional Chaining

Optional chaining is the way by which we try to retrieve a values from a chain of optional values. Let us take the following example classes.

[code language=”swift”]class School {
var director:Person?
}

class Person {
var name: String = ""
init(name: String) {
self.name = name
}
}
[/code]

 

[code language=”swift”]
var school = School()
var person = Person(name: "Jason")
school.director = person
school.director?.name
[/code]

The director property in School class is optional, when you try to access subsequent values from director property becomes optional (? mark after director when accessing name property). You can handle these optionals as shown below.

[code language=”swift”]
if let name = school.director?.name {
println("Director name is \(name)")
} else {
println("Director yet to be assigned")
}[/code]

Filed Under: Apple, ios Tagged With: Apple, Optional bindings, Optional chaining, Swift

How to display line numbers in Xcode

April 30, 2015 By Ravi Shankar Leave a Comment

Listed below are the steps to display line number in Xcode editor window. This is quite useful when you are working in a ground and want to communicate the line number of statement to other members.

Click Xcode menu option and select Preferences from the menu list

201504301024.jpg

In the Preferences window, click Text Editing tab.

201504301026.jpg

Then mark the check box with caption as Show Line numbers. Now you should be able to see the line numbers in Xcode editor window.

201504301027.jpg

Filed Under: Develop, ios, Xcode Tagged With: Line numbers, Xcode

XCode Playground Overview

April 30, 2015 By Ravi Shankar 1 Comment

Playground is an interactive work environment that allows you to see the values in the sidebar for the written code. As and when you make changes to your code the sidebar reflects the changed result. Listed below are some examples written using Swift language in Playground

Sum of n numbers

[code language=”swift”]var sum = 0

for i in 0…10 {
sum += i
}
sum[/code]

Fibonacci Series

[code language=”swift”]
var fibonacci = 0
var temp1 = 1
var temp2 = 0

println(fibonacci)[/code]

[code language=”swift”]
for j in 0…10 {
temp2 = fibonacci
fibonacci += temp1
temp1 = temp2
println(fibonacci)
}[/code]

In the below screenshot, you can observe that the sidebar displaying the values for the variables.

201406191109.jpg

 

201406191114.jpg

 

Similarly the console output displays the message written using println statements And by clicking the Value History option, the timeline feature is displayed for that expression. Console Output, Timeline can be accessed using the Assistant Editor.

201406191115.jpg

Pin the Result

Playground allows to pin the result to the editor window using the Show result option. The playground also allows users the take look at the values using the Quick Look option as shown in the below screenshot. Quick Look can display colours, Strings (plain and attributed), Images, Views, Arrays and Dictionaries, Points, rects, sizes, Bezier Paths, URLs/WebView, Classes and Structs.

201406191133.jpg

Adding images to playground

    We can add images to playground by following the below mentioned steps

    Step 1: Click View menu and select Show File Inspector and Utilities

    201505010639.jpg

    Step 2: Under File Inspector, click Full Path option to access location of the playground file.

    201505010642.jpg

    Step 3: Right click on the file and select Show Package Contents

    201505010651.jpg

    Step 4: Create a folder with name as Resources

    201505010654.jpg

    Step 5: Copy the required image file under Resources folder. For this demo, I have copied a file named as funny_image of type PNG.

    Go to your Playground file and add the following line of code to access the file.

    [code language=”swift”]
    // Add image to playground.

    let image = UIImage(named: "funny_image”)[/code]

    Quick look option should now display the image as shown below.

    201505010659.jpg

    Playground Utilities

    • XCPShowView – Show live views in timeline.
    • XCPSetExecutionShouldContinueIndefinitely. – Allows execution to continue even after reaching playground’s top level code.
    • XCPCaptureValue – Manually capture values.
    • XCPSharedDataDirectoryPath – Retrieves the directory path which contains the shared data between all playgrounds

    In order use the above mentioned playground utilities, we need to import XCPlayground module. Let us see couple of examples for this module.

    XCPShowView

    Add the following code to Playground, which creates a UIView with background colour as Red. And by using XCPShowView, we will add this view to the playground timeline.

    [code language=”swift”]// Add image to playground.

    let image = UIImage(named: "funny_image")
    import XCPlayground
    let demoView = UIView(frame: CGRectMake(0, 0, 250, 250))
    demoView.backgroundColor = UIColor.redColor()
    XCPShowView("MyView", demoView)[/code]

    XCPShowView accepts two parameters, an identifier for the View and the actual View itself.

    201505010711.jpg

    XCPSetExecutionShouldContinueIndefinitely

    Let us see an example of Asynchronous call by calling a web service that returns your IP details.

    [code language=”swift”]// Making Asynchronous call in Playground

    XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)

    let url = NSURL(string: "http://www.telize.com/geoip")

    NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -&gt; Void in

    if error == nil {
    var error:NSError?
    if let result = data {
    if let dict = NSJSONSerialization.JSONObjectWithData(result, options: NSJSONReadingOptions.AllowFragments, error: &amp;error) as? NSDictionary {
    println(dict)
    } else {
    println("Error Processing data")
    }
    }
    } else {
    println(error.localizedDescription)
    }
    }).resume()
    [/code]

     

    You need to make sure the execution is continued until you receive the information from callback method. This is done by adding XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true). The service result will be printed to your console as shown below.

    [code language=”plain”]
    {
    "area_code" = 0;
    asn = AS24560;
    "continent_code" = AS;
    country = India;
    "country_code" = IN;
    "country_code3" = IND;
    "dma_code" = 0;
    ip = "182.65.61.59";
    isp = "Bharti Airtel Ltd., Telemedia Services";
    latitude = 20;
    longitude = 77;
    offset = 5;
    timezone = "Asia/Kolkata";
    }

    [/code]

     

    Playground Limitations

    • Playground cannot be used for performance testing.
    • Does not support User Interaction.
    • Does not support On-device execution.
    • Cannot use your app or framework code.
    • Does not support custom entitlements.

    Filed Under: ios, Xcode Tagged With: Console Output, Playground, Quick Look, Value History, Xcode

    Retrieve list of Twitter followers using Swift

    April 21, 2015 By Ravi Shankar 5 Comments

    This article provides details about the the steps required to retrieve the followers in from your twitter account. You will learn the following by going through this article

    1. Use oAuth to retrieve bearer token.
    2. Retrieve twitter followers using API call.
    3. Last 20 followers name and profile image will be displayed in a tableview.

    Download the source code from here.

    201504202245.jpg

    Consumer Key and Consumer Secret

    First step is to register your app in apps.twitter.com and get the Consumer Key and Consumer Secret from Application Settings.

    Service Wrapper

    Now create a service wrapper which retrieves the bearer token and uses the retrieved token for the service call. In this example the service call will be made to retrieve followers of your Twitter account.

    [code language=”swift”]public class TwitterServiceWrapper:NSObject {
    let consumerKey = “”
    let consumerSecret = “”
    let authURL = “https://api.twitter.com/oauth2/token”
    }[/code]

    Create a TwitterServiceWrapper class with constants for storing the consumer key, consumer secret and oAuth URL. Replace the consumer_key and consumer_secret from your apps.twitter.com account. Next add the following function to retrieve the bearer token using base64 encoded string. We have used Application – only authentication for this example, for more info refer to this documentation.

    [code language=”swift”]// MARK:- Bearer Token

    func getBearerToken(completion:(bearerToken: String) -&gt;Void) {
    var request = NSMutableURLRequest(URL: NSURL(string: authURL)!)
    request.HTTPMethod = “POST”
    request.addValue(“Basic “ + getBase64EncodeString(), forHTTPHeaderField: “Authorization”)
    request.addValue(“application/x-www-form-urlencoded;charset=UTF-8”, forHTTPHeaderField: “Content-Type”)
    var grantType = “grant_type=client_credentials”
    request.HTTPBody = grantType.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)

    NSURLSession.sharedSession() .dataTaskWithRequest(request, completionHandler: { (data: NSData!, response:NSURLResponse!, error: NSError!) -&gt; Void in

    var errorPointer : NSErrorPointer = nil

    if let results: NSDictionary = NSJSONSerialization .JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments , error: errorPointer) as? NSDictionary {

    if let token = results[“access_token”] as? String {
    completion(bearerToken: token)
    } else {
    println(results[“errors”])
    }
    }

    }).resume()
    }

    // MARK:- base64Encode String

    func getBase64EncodeString() -&gt; String {

    let consumerKeyRFC1738 = consumerKey.stringByAddingPercentEscapesUsingEncoding(NSASCIIStringEncoding)

    let consumerSecretRFC1738 = consumerSecret.stringByAddingPercentEscapesUsingEncoding(NSASCIIStringEncoding)

    let concatenateKeyAndSecret = consumerKeyRFC1738! + ”:” + consumerSecretRFC1738!

    let secretAndKeyData = concatenateKeyAndSecret.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)

    let base64EncodeKeyAndSecret = secretAndKeyData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)

    return base64EncodeKeyAndSecret!
    }
    [/code]

     

    Now add the following functions which would use the bearer token to make the service call then process the results and store them in TwitterFollower struct.

    [code language=”swift”]// MARK:- Service Call

    func getResponseForRequest(url:String) {
    var results:NSDictionary
    getBearerToken({ (bearerToken) -&gt; Void in
    var request = NSMutableURLRequest(URL: NSURL(string: url)!)
    request.HTTPMethod = “GET”
    let token = “Bearer “ + bearerToken
    request.addValue(token, forHTTPHeaderField: “Authorization”)

    NSURLSession.sharedSession() .dataTaskWithRequest(request, completionHandler: { (data: NSData!, response:NSURLResponse!, error: NSError!) -&gt; Void in

    self.processResult(data, response: response, error: error)
    }).resume()
    })
    }

    // MARK:- Process results
    func processResult(data: NSData, response:NSURLResponse, error: NSError?) {

    var errorPointer : NSErrorPointer = nil

    if let results: NSDictionary = NSJSONSerialization .JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments , error: errorPointer) as? NSDictionary {

    if var users = results["users"] as? NSMutableArray {
    for user in users {
    let follower = TwitterFollower(name: user["name"] as! String, url: user["profile_image_url"] as! String)
    self.delegate?.finishedDownloading(follower)
    }

    } else {
    println(results["errors"])
    }
    }
    }
    [/code]

     

    TwitterFollowerDelegate

    We also need to create a protocol in TwitterServiceWrapper class. This will inform the delegates once the data is downloaded from the service

    [code language=”swift”]protocol TwitterFollowerDelegate{
    func finishedDownloading(follower:TwitterFollower)
    }[/code]

    TwitterFollower – Place holder struct

    TwitterFollower struct will just act as a place holder for storing followers’s name, profile URL and description. TwitterFollower struct looks as shown below.

    [code language=”swift”] struct TwitterFollower {
    var name: String?
    var description: String?
    var profileURL: NSData?

    init (name: String, url: String) {
    self.name = name
    let pictureURL = NSURL(string: url)
    profileURL = NSData(contentsOfURL: pictureURL!)
    }
    }[/code]

    Add TableViewController

    Now finally we use the followers data retrieved from the service and displayed in a tableview. TwitterFollowerController is a UITableViewController which conforms to TwitterFollowerDelegate protocol. We create an instance of TwitterServiceWrapper class and pass the request URL for retrieving the followers details in viewDidLoad method.

    [code language=”swift”]class TwitterFollowerController: UITableViewController, TwitterFollowerDelegate {
    var serviceWrapper: TwitterServiceWrapper = TwitterServiceWrapper()
    var followers = [TwitterFollower]()

    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
    super.viewDidLoad()
    serviceWrapper.delegate = self
    activityIndicator.startAnimating()
    serviceWrapper.getResponseForRequest(“https://api.twitter.com/1.1/followers/list.json? screen_name=rshankra&amp;skip_status=true&amp;include_user_entities=false”)
    }[/code]

    Implement the Table View Data source methods as shown below

    [code language=”swift”]// MARK: – Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int {
    return 1
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
    let numberOfRows = followers.count
    return numberOfRows
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier(“reuseIdentifier”, forIndexPath: indexPath) as! UITableViewCell

    let follower = followers[indexPath.row] as TwitterFollower
    cell.imageView?.image = UIImage(data: follower.profileURL!)
    cell.textLabel?.text = follower.name

    return cell
    }[/code]

    The data for followers array will be populated in the TwitterFollowerDelegate method.

    [code language=”swift”] // MARK: – TwitterFollowerDelegate methods

    func finishedDownloading(follower: TwitterFollower) {
    dispatch_async(dispatch_get_main_queue(), { () -&gt; Void in
    self.followers.append(follower)
    self.tableView.reloadData()
    self.activityIndicator.stopAnimating()
    self.activityIndicator.hidden = true
    })
    }[/code]

    We need to make sure that the reloading of data is done in the main thread by calling

    [code language=”plain”]dispatch_async(dispatch_get_main_queue()[/code]

    Download the source code from here.

    Filed Under: Apple, ios, iPhone, Programming Tagged With: Apple, oAuth, Twitter API, Twitter Followers

    How to record and play sound in Swift

    April 12, 2015 By Ravi Shankar 10 Comments

    In this tutorial, we are going to see the required steps to record and play sound in Swift Programming language using AVAudioRecorder and AVAudioPlayer

    Download source code from github (SoundController.swift)

    User Interface

    The user interface for this demo is simple with two buttons, one for recording and another for playing sound.

    201504121626.jpg

    Create corresponding IBAction and IBOutlets from the two button in the View Controller.

    @IBOutlet weak var recordButton: UIButton!

    @IBOutlet weak var playButton: UIButton!

    @IBAction func recordSound(sender: UIButton)

    @IBAction func playSound(sender: UIButton)

    Dual Purpose Buttons

    The Record button will be used to record and stop recording. Similarly the Play button will used to Play and Stop the audio.

    Class level var and let declaration

      var soundRecorder: AVAudioRecorder!

    var soundPlayer:AVAudioPlayer!

      

    let fileName = “demo.caf”

    Declare two class level variable for holding an instance of AVAudioRecorder and AvAudioPlayer. Also create constant for holding the file name.

    Create Sound file path

    For this demo, the sound file will be created under the Cache directory using the name defined in the constant. Add these two function to your class

      func getCacheDirectory() -> String {

      

    let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory,.UserDomainMask, true) as [String]

      

    return paths[0]

    }

      

    func getFileURL() -> NSURL {

      

    let path = getCacheDirectory().stringByAppendingPathComponent(fileName)

    let filePath = NSURL(fileURLWithPath: path)

      

    return filePath!

    }

    The getCacheDirectory retrieves the caches directory and getFileURL appends the file name with the cache directory.

    Setup Recorder

    Create a new function that prepares the recorder and this function will be called during the viewDidLoad operation

    func setupRecorder() {

      

    //set the settings for recorder

      

    var recordSettings = [

    AVFormatIDKey: kAudioFormatAppleLossless,

    AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue,

    AVEncoderBitRateKey : 320000,

    AVNumberOfChannelsKey: 2,

    AVSampleRateKey : 44100.0

    ]

      

    var error: NSError?

      

    soundRecorder = AVAudioRecorder(URL: getFileURL(), settings: recordSettings, error: &error)

      

    if let err = error {

    println(“AVAudioRecorder error: \(err.localizedDescription)“)

    } else {

    soundRecorder.delegate = self

    soundRecorder.prepareToRecord()

    }

    }

    To create an AVAudioRecorder instance, you need to pass three parameters,

    URL– Specifies the path and name of the file where the sound will be recorded.

    settings – Configure AVRecorder settings

    error – Capture error while creating AVRecorder instance.

    If there is no error while creating Audio Recorder, the delegate it set to the View Controller and recorder is prepared for recording. Make sure the View Controller conforms to AVAudioRecorderDelegate

    class SoundController: UIViewController, AVAudioRecorderDelegate {

    Prepare Player

    Add the following function that prepares the AVAudiPlayer to play the recorded sound

    func preparePlayer() {

    var error: NSError?

      

    soundPlayer = AVAudioPlayer(contentsOfURL: getFileURL(), error: &error)

      

    if let err = error {

    println(“AVAudioPlayer error: \(err.localizedDescription)“)

    } else {

    soundPlayer.delegate = self

    soundPlayer.prepareToPlay()

    soundPlayer.volume = 1.0

    }

    }

    AVAudioPlayer instance is created by passing sound file that needs to be played along with pointer to capture errors while creating AVAudioPlayer instance. Make sure the View Controller conforms to AVAudioPlayerDelegate. Then call the prepareToPlay function on the AVAudioPlayer instance.

    Implement IBActions function to record and play sound

    Add the following implementation to the IBAction functions which records and plays sound.

    @IBAction func recordSound(sender: UIButton) {

    if (sender.titleLabel?.text == “Record”){

    soundRecorder.record()

    sender.setTitle(“Stop”, forState: .Normal)

    playButton.enabled = false

    } else {

    soundRecorder.stop()

    sender.setTitle(“Record”, forState: .Normal)

    }

    }

      

    @IBAction func playSound(sender: UIButton) {

    if (sender.titleLabel?.text == “Play”){

    recordButton.enabled = false

    sender.setTitle(“Stop”, forState: .Normal)

    preparePlayer()

    soundPlayer.play()

    } else {

    soundPlayer.stop()

    sender.setTitle(“Play”, forState: .Normal)

    }

    }

    When the Record button is tapped, the name of the button is changed to Stop and starts recording the sound. Similarly when the title is Stop, the recording the stopped and play button is enabled. The same is done when the user taps the play button.

    class SoundController: UIViewController, AVAudioRecorderDelegate, AVAudioPlayerDelegate {

    Implement AVAudioRecorderDelegate methods

      func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) {

    playButton.enabled = true

    recordButton.setTitle(“Record”, forState: .Normal)

    }

      

    func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder!, error: NSError!) {

    println(“Error while recording audio \(error.localizedDescription)“)

    }

    Implement AVAudioPlayerDelegate methods

      func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {

    recordButton.enabled = true

    playButton.setTitle(“Play”, forState: .Normal)

    }

      

    func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer!, error: NSError!) {

    println(“Error while playing audio \(error.localizedDescription)“)

    }

    Now you are good to go and try this demo. You can download the source code for recording and playing audio in swift from github.

    Filed Under: Develop, ios, Programming, Xcode Tagged With: AvAudioPlayer, AVAudioRecorder, Xcode

    UITextFieldDelegate in Swift

    April 7, 2015 By Ravi Shankar Leave a Comment

    This is a beginners tutorial on UITextFieldDelegate in Swift. We are going to see how to use UITextFieldDelegate by writing a Simple Interest Calculator.

    201504071303.jpg

    Download the source code from here

    This calculator uses UILabels and TextFields for displaying and accepting amount and interest. We are going to use the UITextFieldDelegate method to navigate from “Principal Amount” to “Rate of Interest”. And when the user taps done on “Rate of Interest” UITextField, the interest is calculated and displayed on the corresponding label.

    Source Code

    import UIKit

    class TextFieldDemoController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var amountTextField: UITextField!

      

    @IBOutlet weak var rateTextField: UITextField!

      

    @IBOutlet weak var interestLabel: UILabel!

      

    var textFields:[UITextField] = []

      

    override func viewDidLoad() {

    super.viewDidLoad()

      

    self.amountTextField.delegate = self

    self.rateTextField.delegate = self

      

    textFields = [amountTextField, rateTextField]

      

    }

    override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.

    }

      

    //MARK :- TextField Delegate

      

    func textFieldShouldReturn(textField: UITextField) -> Bool {

      

    var currentTextField = textFields[0]

      

    if (currentTextField == textField) {

    currentTextField = textFields[1]

    currentTextField.becomeFirstResponder()

    } else {

    currentTextField.resignFirstResponder()

    interestLabel.text = “\(calculateInterest())“

    }

      

    return true

    }

      

    //MARK :- Calculation

      

    func calculateInterest() -> Double {

    let amount: Double = (amountTextField.text as NSString).doubleValue

    let rate:Double = (rateTextField.text as NSString).doubleValue

      

    return amount * rate

    }

    }

    Step 1: Make sure your view controller class conforms to UITextFieldDelegate

    Step 2: In ViewDidLoad method, set the delegate for the textfields to self (ViewController)
    Step 3: Implement textFieldShouldReturn(textField: UITextField) -> Bool(UITextFieldDelegate method) and the code that makes the UITextField FirstResponder and calculates the Interest once the values are entered.
    Download the source code from here

    Filed Under: Apple, Develop, ios, Programming, Xcode Tagged With: Apple, textFieldShouldReturn, UITextFieldDelegate, Xcode

    1. Pages:
    2. «
    3. 1
    4. 2
    5. 3
    6. 4
    7. 5
    8. 6
    9. 7
    10. 8
    11. 9
    12. 10
    13. »
    « Previous Page
    Next Page »

    Primary Sidebar

    TwitterLinkedin

    Recent Posts

    • How to block keywords in Jio broadband
    • How to disable opening an app automatically at login in Mac
    • How to set preferred Wifi network on Mac
    • Attribute Unavailable: Estimated section warning before iOS 11.0
    • How to recover Firefox password from Time Machine backup

    Pages

    • About
    • Privacy Policy
    • Terms and Conditions

    Copyright 2022 © rshankar.com

    Terms and Conditions - Privacy Policy