• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

Apple

Get your current address in Swift (Swift 5)

November 7, 2019 By Ravi Shankar 22 Comments

In this Swift tutorial, we will see the steps required for using CoreLocation framework and retrieve the latitude and longitude of the location. Then use the CLGeocoder to reverse geocode the latitude and longitude details. This is a very basic tutorial that retrieves the location details on tap of a button and displays the information on the screen.

Updated :- The source has now been to updated to show the address details in TextFields.

Click File -> New and select Project sub menu list.

201407251656.jpg

In the Choose a template screen, select Single View Application and click Next button.

201407251657.jpg

Enter the product name as WhereAmI and select the language as Swift then click Next. Select a folder and create the new project and that folder.

201407251658.jpg

Navigate to ViewController.swift file and add a new function with name as findMyLocation after viewDidLoad function.

@IBAction func findMyLocation(sender: AnyObject) {

}

Navigate to Main.storyboard file, drag and drop Button from the Object Library on to the View Controller. Using the attributes inspector, change the name of the button to “Where Am I?”. If you need then change the background and text colour for the button. Then centre align the button both vertically and horizontally. Use the Resolve Auto Layout Option and pick Reset to Suggested Constraints.

201407251707.jpg

Navigate to Connections Inspector and connect the button to the findMyLocation action under Received Actions (Touch Up Inside event).

201407251711.jpg

Click the Project under Project Navigator and navigate to Build Phases. Click the + sign under Link Binary With Libraries and pick CoreLocation.framework from the list.

Add CoreLocation framework to Swift project201407251718.jpg

CoreLocation in Swift

Now navigate back to ViewController.swift file, add import CoreLocation after UIKit. Then we need to assign the current class as the delegate for CLLocationManagerDelegate. This is required because we will be using couple of delegate methods from CLLocationManager.

class ViewController: UIViewController, CLLocationManagerDelegate {

Define a constant for CLLocationManager after the class declaration.

let locationManager = CLLocationManager()

Navigate to IBAction function findMyLocation and add the following code

locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()

The above lines sets the class as delegate for locationManager, specifies the location accuracy and starts receiving location updates from CoreLocation. In order to get the location updates we need to implement the delegate functions of CLLocationManager, didUpdateLocations and didFailWithError

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
}

didUpdateLocations function is triggered when new location updates are available. Similarly didFailWithError is called when there is a problem receiving the location updates. Let us first start implementing the simpler one i.e didFailWithError function. When there is an error, we are going to log the message to the console.

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
	println("Error while updating location " + error.localizedDescription)
}

Then update didUpdateLocations function with the following code, also add a new function for printing the location details.

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
		if error {
			println("Reverse geocoder failed with error" + error.localizedDescription)
			return
		}

		if placemarks.count > 0 {
			let pm = placemarks[0] as CLPlacemark
			self.displayLocationInfo(pm)
		} else {
			println("Problem with the data received from geocoder")
		}
	})
}

func displayLocationInfo(placemark: CLPlacemark) {
	if placemark != nil {
		//stop updating location to save battery life
		locationManager.stopUpdatingLocation()
		println(placemark.locality ? placemark.locality : "")
		println(placemark.postalCode ? placemark.postalCode : "")
		println(placemark.administrativeArea ? placemark.administrativeArea : "")
		println(placemark.country ? placemark.country : "")
	}
}

in the didUpdateLocations function, we pass the location co-ordinates to

 CLGeocoder().reverseGeocodeLocation

. Then check for error and process the location array (placemarks). Then for displaying the location details, we pass the placemark detail to displayLocationInfo function.

Add key to Info.plist for request permission to User’s location

In order to use the user’s location you need to request permission from the user by adding the keys “NSLocationWhenInUseUsageDescription” or “NSLocationAlwaysUsageDescription” to your Info.plist file, with the value blank or optionally a message included in the prompt to the user. One of those two key is required in iOS 8 to ask for your location.

Testing Location in Simulator

It is not possible to test current location with simulator. So we need to define a custom location or use the location already defined for debug purpose. When an app tries to access the location services on a simulator it displays the following popup.

Current Location Simulator Xcode 6

Here is a workaround to test the app using Xcode 11. Run the app on the a Simulator and tap “Find My Location” button. Nothing will happen as the app has not been given permission to use Location Services on Simulator.

201407251956.jpg

Click Debug menu then Location and select Apple from the sub menu list. Still nothing happens with the app and no messages are written to the console.

201407251957.jpg

Now click Hardware menu and select Home from menu list.

201407251959.jpg

Tap the Settings icon on Simulator -> Privacy -> Location -> Tap , select Always to allow the app to access the location.

201407252003.jpg201407252005.jpg

Now you should see Apple address details in the Console Output.

201407252008.jpg

You can also try out other location using the Simulate Location option.

Simulate location in Xcode 6 simulator

Hopefully the testing should be lot easier after issue with “Allow to use Current Location” is fixed.

Source from GitHub

Filed Under: Apple, Develop, ios, Programming, Xcode Tagged With: Apple, CoreLocation, Swift, Xcode

Add line numbers in Word 2013, Word 2010 and Word 2007

September 27, 2015 By Ravi Shankar Leave a Comment

Microsoft Word users can add line numbers to a word document using the options available as part of Page Layout menu. In this tutorial we will see the steps for adding line number in Word 2013 and Word 2011 for Mac.

How to add line numbers in Word 2007, Word 2010, Word 2013 and Word 2011 for Mac

Word 2007 Word 2010 and Word 2013

Word 2010 allows users to add line numbers to a word document. This can be done using the Page Layout menu option. For example if you have the following text in your document and you want insert line numbers for each line then you use this feature.

image

To add line numbers for above paragraph, from Home menu click the Page Layout menu option and then navigate to Page Setup section.

Page Layout Menu in Word 2013 and Word 2010

In the Page Layout section, click the drop down arrow next to Line Numbers menu option. This would display the following menu options.

Line numbers in Word 2013 and Word 2010

Now select Continuous from the list available menus and this would insert the line numbers in the Word document as shown below

Document with line numbers in Word 2010 and Word 2013

The other line numbers options includes

  • Restart Each Page – To restart line numbers after each page.
  • Restart Each Section – To restart line numbers after each section.
  • Suppress for Current Paragraph – to remove line numbers for the selected paragraph.

Word 2011 for Mac

Step 1: Open the document for which you want to add line number.

Word 2011 for Mac Layout Menu

Step 2: Click Layout menu and navigate to Text Layout section.

Step 3: Now click the Line Numbers option under Text Layout. This should display the following drop down list.

Word 2011 for Mac Continuous numbers

Step 4: Select Continuous from the Line numbers drop down list to add line numbers. You can also customise Line numbers by use other options in the list.

Show line numbers in document

If you are looking for advanced line number options then click More Line Numbering.

More line numbers option

Display of line number in status bar

If you just want to find out the current line number while editing a document then you can use line number option available as part of status bar for this purpose.

Word 2007, Word 2010 and Word 2013

Microsoft Word 2007 and Word 2010 provides option to display the line numbers in a word document. This would be a useful feature when you want to restrict your content based on the number of lines written in the document. If the status bar does not show the line numbers, then right click on the Status bar and select Line number.

Display line number in status bar in Word 2013, Word 2010 and Word 2007

After selecting Line Number option in the Customize Status Bar context menu, the status bar would display the line number as shown below.

Show line numbers in Word status bar

Word 2011 for Mac

Word 2011 for Mac does not support the display of line number in status bar. This option is available in Window’s version of Microsoft Word but not in Mac OS X.

Also See: How to auto populate random sentences in Word 2010

Filed Under: Apple, Mac, MS Office, Office 2010, Office 2013, Word 2007, Word 2010, Word 2013 Tagged With: Apple, Line numbers, Mac, Page Layout, Show Line numbers, Status Bar, Word 2011 for Mac

Tuples, Enums and Protocols in Swift

May 14, 2015 By Ravi Shankar Leave a Comment

Tuples in Swift allows user to assign group of values to a variable, constant and even return parameter of a function. In the below example, a employee constant is assigned Int and String values. And to access these parameters, we need to use .0 and .1

[code language=”swift”]let employee = (103, “Deepak”)
employee.0
employee.1[/code]

Now let us say you want to assign proper name for these parameters so that you could access these values using those names instead of 0 and 1.

[code language=”swift”]let employee = (id:103, name:“Deepak”)
employee.id
employee.name[/code]

Here id and name are parameter names provided for employee id and employee name. You can also declare the data types for the tuple values like Int and String

[code language=”swift”]let employee:(id:Int, name:String = (102, “Deepak”)
employee.id
employee.name[/code]

Tuples and switch cases are powerful combination, look at an example below where Tuple has been used with switch cases. The _ is used for matching any values.

[code language=”swift”]let employee:(id:Int, name:String) = (102, “Deepak”)
switch (employee) {
case (103…105,_):
println(“developer”)
case (106…108,_):
println(“tester”)
case (_,“Deepak”):
println(“CEO”)
default:
println(“Contractor”)
}[/code]

Enums

Enum in Swift allows users to group related values to a single data type. Swift enum has lot of new features compared to its predecessor Objective-C. Let us see this with an example enum type for all Months in a year.

[code language=”swift”]enum Months {
case January, February, March, April, May, June, July, August, September, October, November, December
}

enum Month {
case January, February, March, April, May, June, July, August, September, October, November, December
}[/code]

Now you can define a variable or a constant of type month as shown below.

[code language=”swift”]let currentMonth = Month.May[/code]

And variable or constant is declared with the data type then you can use the short form.

[code language=”swift”]let currentMonth:Month = .May[/code]

Enum with Raw Value

Enum in Swift can be assigned a RawValue when declaring and the value can be of any data type. Let us day you want to specify the String value of each Month

[code language=”swift”]enum Month: String {
case January = “January”, February = “February”, March = “March”, April = “April”, May = “May”, June = “June”, July = “July”, August = “August”, September = “September”, October = “October”, November = “November”, December = “December”
}[/code]

The RawValue can be printed by accessing .rawValue on the enum variable or constant.

[code language=”swift”]let currentMonth:Month = .May
currentMonth.rawValue[/code]

Enum with Associated Value

Same like RawValue, enum can also have associated value and of data type.

[code language=”swift”]enum Month {
case January(String), February(String), March(String), April(String), May(String), June(String), July(String), August(String), September(String), October(String), November(String), December(String)
}

let currentMonth:Month = .May(“Summer Vacation”)

switch currentMonth {
case .May(let message):
println(message)
default:
println(“No Values”)
}[/code]

In the above example, Month enum values are declared with an associated value of data type String. And while assign the enum value the associated value is also provided to the currentMonth constant. Using the switch the associated value is retrieved.

Enum can have member function

Enum in Swift can also have member function. In the below example code, we have declared the Month enum with rawValue of type Int. Now add a member function to calculate the number of months left from the currently assigned value.

[code language=”swift”]enum Month: Int {
case January = 1, February, March, April, May, June, July, August, September, October, November, December func monthsLeftForYearEnd() -> Int {
return Month.December.rawValue – self.rawValue
}
}

let month: Month = .May
month.monthsLeftForYearEnd()[/code]

Constant month is assigned a enum value of .May and you can find out the number of months left for the year end by accessing the monthsLeftForYearEnd.

Enum can have Initialiser

Swift’s enum can have initialiser too where you can set the default enum value or do some initial processing. If you add init function as shown below, the default enum value will be set to July.

[code language=”swift”]enum Month: Int {
case January = 1, February, March, April, May, June, July, August, September, October, November, December
init() {
self = .July
}

func monthsLeftForYearEnd() -> Int {
return Month.December.rawValue – self.rawValue
}
}

let month = Month()
month.monthsLeftForYearEnd()[/code]

Protocols

Protocol in Swift defines the contract for a class or struct. This is similar to the interface in other languages like java. Protocol only defines the member function or variables and the actual implementation should be done in the conforming class or struct. Protocol can be be useful in the following ways

  • To add common behaviour across related or unrelated classes.
  • Supports in the implementation of delegation pattern

Let us see a typical example of protocol in Swift where we defining a Protocol called LivingThings with one method eat.

[code language=”swift”]protocol LivingThings {
func eat() -> String
}[/code]

Any class or struct conforming to this Protocol should add implementation to eat method. In the below code example, we have got two classes Animal and Human which conform to LivingThings. implementation for the eat method has been added to both the classes.

[code language=”swift”]class Animal: LivingThings {
func eat() -> String {
return “Animal Food"
}
}

class Human: LivingThings {
func eat() -> String {
return "Human Food"
}
}

let john = Human()
john.eat()

let cat = Animal()
cat.eat()[/code]

If a class conforming to a Protocol does not implement the required methods then you will find error message “error: type ‘Human’ does not conform to protocol ‘LivingThings’”

Protocol with Optional Methods

In Swift, Protocol with optional method can be defined by specifying the optional before the method definition and adding @objc keyword before protocol. Listed below is an example with Speakable protocol that has an optional method speak

[code language=”swift”]
protocol LivingThings {
func eat() -> String
}

@objc protocol Speakable {
optional func speak() -> String
}

class Human: LivingThings, Speakable {
func eat() -> String {
return "Human Food"
}

func speak() -> String {
return "Human can Speak"
}
}

let john = Human()
john.eat()
john.speak()[/code]

Protocol and Delegation Pattern

A delegate pattern is used when you want a class to act on behalf of another class or for a callback mechanism. In the below code example we have defined a protocol (ImportDataDelegate) with two methods startImport and finishedImport. The DataImport class conforms to this Protocol and adds implementation to these methods. The DemoImport class acts on behalf of DataImport class by declaring a variable delegate of type ImportDataDelegate.

[code language=”swift”]protocol ImportDataDelegate {
func startImport()
func finishedImport()
}

class DataImport: ImportDataDelegate {
func startImport() {
println("Import started")
}

func finishedImport() {
println("Import finished")
}
}

class DemoImport {
var delegate: ImportDataDelegate?

func startProcess() {
delegate?.startImport()
println("Doing some work …")
delegate?.finishedImport()
}
}[/code]

This is how you pass the DataImport class to delegate variable of the DemoImport.

[code language=”swift”]let demoImport = DemoImport()
demoImport.delegate = DataImport()
demoImport.startProcess()[/code]

Filed Under: Apple, Develop, ios, Programming Tagged With: Apple, delegate pattern, Optional Methods, Protocol

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

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

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. 1
  3. 2
  4. 3
  5. 4
  6. 5
  7. 6
  8. »
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