• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

Xcode

Add annotations and Polyline to MapView in Swift

July 6, 2015 By Ravi Shankar 21 Comments

In this article, we will see the instructions for adding annotation to MapView, Draw Polylines and Zoom to a region in Swift. Let us see this by adding stations to a Map for Chennai subrban trains and connect these stations using Map Overlay.

Project Setup

 

Create a new project by selecting Single View Application as the project template.

Enter the required information such project name, organization identifier etc.. as shown in the below screenshot. Then save the project in your desired location.

Add MapKit View

 

Navigate to Project navigator and select Main.storyboard file.

We are not using the Auto Layout for this demo, hence disable Use Auto Layout and disable size classes using the options available as part of the File Inspector

Drag and drop MapKit View from object library to the View Controller and make sure to resize the MapView to full view. Add IBOutlet in the ViewController for the MapKit and connect it to the MapKit View in the Interface builder. Also add import MapKit to include MapKit framework for your project.

[code language=”swift”]@IBOutlet weak var mapView: MKMapView!
[/code]

Now if you do a build and run the project in iPhone 6 simulator, you should see the following on simulator.

Zoom to specified region

 

Add the follwing piece of code in ViewController.swift file. And call this function from ViewController’s viewDidLoad function.

[code language=”swift”]//MARK:- Zoom to region

func zoomToRegion() {

let location = CLLocationCoordinate2D(latitude: 13.03297, longitude: 80.26518)

let region = MKCoordinateRegionMakeWithDistance(location, 5000.0, 7000.0)

mapView.setRegion(region, animated: true)
}
[/code]

 

CLLocationCoordinate2D is created by specifying latitude and longitude of the zoom location. Then using MKCoordinateRegionMakeWithDistance set the distance around the speicifed location. Then this region will set as the region for the MapView. Build and run the project should show Map zooming to the speicifed region as shown below.

 

Add plist file to project.

 

All the station details such as title, latitude and longitude are stored in a plist file. You can download the plist from gitHub. Right click on the Project folder (Project navigator) and select “Add Files to <Project name>” option. And select Copy items if needed option while adding the file.

The sample data structure of the plist file is shown below

 

Add place holder class Station

Create a new model class for holding the station data. This class should conform to MKAnnotation and NSObject protocol.

[code language=”swift”]import MapKit

class Station: NSObject, MKAnnotation {
var title: String?
var subtitle: String?
var latitude: Double
var longitude:Double

var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}

init(latitude: Double, longitude: Double) {
self.latitude = latitude
self.longitude = longitude
}
}[/code]

 

This class has properties for title, subtitle, latitude, longitude and coordinate. Any mappoint should have coordinate for the adding it to the map. This property is mandatory and it is defined in MKAnnotation protocol. The initializer in the class accepts the latitide and longitude details as they are needed for creating the coordinates.

Add annotation to MapKit

We need to iterate through the plist file and create annotation for each stations. Add the following function to ViewController.swift which does the same.

[code language=”swift”]//MARK:- Annotations

func getMapAnnotations() -&gt; [Station] {
var annotations:Array = [Station]()

//load plist file
var stations: NSArray?
if let path = NSBundle.mainBundle().pathForResource("stations", ofType: "plist") {
stations = NSArray(contentsOfFile: path)
}

//iterate and create annotations
if let items = stations {
for item in items {
let lat = item.valueForKey("lat") as! Double
let long = item.valueForKey("long")as! Double
let annotation = Station(latitude: lat, longitude: long)
annotation.title = item.valueForKey("title") as? String
annotations.append(annotation)
}
}

return annotations
}
[/code]

Add the following piece of code in viewDidLoad function.

[code language=”swift”]let annotations = getMapAnnotations()
// Add mappoints to Map
mapView.addAnnotations(annotations)[/code]

Now if you build and run the project, you should see the map with annotations. And on tapping any mappoint should display the title for that station.

Add Polyline to MapView

In order add Polyline overlay to map, we need to implement function defined in MKMapViewDelegate protocol. Add MkMapViewDelegate in the class declaration after UIViewController.

[code language=”swift”]class ViewController: UIViewController, MKMapViewDelegate {[/code]

Then make sure to set the delegate property of the mapview to self so that the ViewController can implement and handle the MKMapViewDelegate functions. Add the following piece of code in viewDidLoad function after the annotations.

[code language=”swift”]
mapView.delegate = self
// Connect all the mappoints using Poly line.

var points: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]()

for annotation in annotations {
points.append(annotation.coordinate)
}
var polyline = MKPolyline(coordinates: &amp;points, count: points.count)
mapView.addOverlay(polyline)
[/code]

create a array of CLLocationCoordinate2D by iterating through annotations. Then create an instance of MKPolyline class by passing array of CLLocationCoordinate2D and count of coordinates. Finally add this polyline to mapView overlay.

Implement the rendererForOverlay MKMapViewDelegate function and return an insatnce of MKPolylineRenderer class

[code language=”swift”]
//MARK:- MapViewDelegate methods

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -&gt; MKOverlayRenderer! {
if overlay is MKPolyline {
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 5
return polylineRenderer
}

return nil
}
[/code]

 

Now build and run the app should display the Polyline on the Map.

Download the source code from here

Filed Under: ios, Programming, Swift, Xcode

Navigation Controller in iOS

July 1, 2015 By Ravi Shankar 1 Comment

Navigation contollers are quite commonly used in iOS App. Navigation Controllers contain stack of view controllers and provide a drill down approach for accessing the child view controllers. The top bar in a navigation controller is called the navigation bar which normally contains the title of the screen. The navigation bar in child View Controller will have a back button that appears automatically and will take you to Root ViewController.

Listed below are screenshots of apps with navigation controller.

Example Apps

 

Calendar App

Music App

The objective of this Navigation Contorller article is to explain the following

  1. How to embed ViewController inside Navigation Controller
  2. Add Title to Navigation Bar
  3. Creating a Push Segue
  4. ViewController transitions using Segue and programmatically
  5.  Programmatically dismiss ViewController.
  6. Add toolbars to navigation controller

Project Setup

Let us see the functioning of navigation controller with an example project. This project displays list of different colours and drill down on each colours will set the background of the ViewController to choosen colour.

Create a new Xcode project selecting tamplate as Single View Application.

In the Choose options for your new project, select Language as Swift.

Embed ViewController inside Navigation Controller

Navigate to Main.storyboard file in the project navigator and select ViewController. Then unmark the check boxes with caption as Use Auto Layout and Use Size Classes (using File Inspector) as this app is onlye for iPhone and not any other devices,

Now embed the ViewContoller inside a navigation contoller by selecting Navigation Contoller option under Editor -> Embed In menu option. The ViewController will be embeded in Navigation Controller as shown below.

Add Colours Enum

Add a new Swift file to the project and name the file and Colours. Open the file for editing and add the following code snippet.

[code language=”swift”]
enum Colours: String {
case Blue = “0000FF”
case Cyan = “00FFFF”
case Gold = “FFD700”
case Green = “008000”
case Khaki = “F0E68C”
case Orange = “FFA500”
case Red = “FF0000”
case Skyblue = “87CEEB”
case Tan = “D2B48C”
case Violet = “EE82EE”

static let allValues = [Blue,Cyan,Gold,Green,Khaki,Orange,Red,Skyblue,Tan,Violet]

func getDisplayName() -> String {
var displayName = “”

switch (self) {
case .Blue:
displayName = “Blue”
case .Cyan:
displayName = “Cyan”
case .Gold:
displayName = “Gold”
case .Green:
displayName = “Green”
case .Khaki:
displayName = “Khaki”
case .Orange:
displayName = “Orange”
case .Red:
displayName = “Red”
case .Skyblue:
displayName = “SkyBlue”
case .Tan:
displayName = “Tan”
case .Violet:
displayName = “Violet”
}
return displayName
}

static func getColours() -> [String] {
var colours:[String] = []

for colour in Colours.allValues {
colours.append(colour.getDisplayName())
}
return colours
}

static func getEnumFromSelectedValue(selectedRow: Int) -> Colours{

var selected:Colours?

switch (selectedRow) {
case Colours.Blue.hashValue:
selected = .Blue
case Colours.Cyan.hashValue:
selected = .Cyan
case Colours.Gold.hashValue:
selected = .Gold
case Colours.Green.hashValue:
selected = .Green
case Colours.Khaki.hashValue:
selected = .Khaki
case Colours.Orange.hashValue:
selected = .Orange
case Colours.Red.hashValue:
selected = .Red
case Colours.Skyblue.hashValue:
selected = .Skyblue
case Colours.Tan.hashValue:
selected = .Tan
case Colours.Violet.hashValue:
selected = .Violet
default:
break
}

return selected!
}

// Credit below function to http://www.anthonydamota.me/blog/en/use-a-hex-color-code-with-uicolor-on-swift/

static func getUIColorFromHex(colorCode: String, alpha: Float = 1.0) -> UIColor{
var scanner = NSScanner(string:colorCode)
var color:UInt32 = 0;
scanner.scanHexInt(&color)

let mask = 0x000000FF
let r = CGFloat(Float(Int(color >> 16) & mask)/255.0)
let g = CGFloat(Float(Int(color >> 8) & mask)/255.0)
let b = CGFloat(Float(Int(color) & mask)/255.0)

return UIColor(red: r, green: g, blue: b, alpha: CGFloat(alpha))
}
}
[/code]

In the above code snippet, we have added enum that holds a list of colours and following functions

  • getDisplayName() – Retrieve the Colour name from Enum value
  • getColours() – Returns the list of colours.
  • getEnumFromSelectedValue() – Return enum on based on selected value
  • getUIColorFromHex() – returns the UIColor object based on Hex Colour code.

Adding UITableView

In order to display different colours, let us add a UITableView to the ViewController (which is embeded in Navigation Controller). Drag and drop a UITableView from Object library to the ViewController. Then set the datasource and delegate property of the tableview to the ViewController. Add IBOutlet TableView variable and connect it to the UITableView in the Interface Builder. If you find difficulty in following these steps check out UITableView demo in Swift.

Setup data for TableView

Add an instance level variable to the ViewController class for storing data

[code language=”swift”]var data:[String] = [String]()[/code]

And in viewDidLoad function add this line data = Colours.getColours() to populate data with the array of colours. Then implement the following UITableViewDataSource methods numberOfRowsInSection and cellForRowAtIndexPath as shown below.

[code language=”swift”]//MARK:- UITableViewDataSource methods

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(“CellIdentifier”, forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = data[indexPath.row]
return cell
}
[/code]

Navigate to Main.storyboard file and add UITableViewCell to the TableView. Make sure to provide identifier for the prototype cell as “CellIdentifier”. Now if you build and run the project you sould see the initial screen with empty navigation bar and with following set of colours

Add Title to Navigation Bar

You can use Interface builder to add title to navigation bar by double clicking on the center of the Navigation bar.

And if you want to add title programmatically then use the following code snippet. Place this code snippet in viewDidAppear function.

[code language=”swift”] navigationItem.title = “Colours”
[/code]

Create Push Segue

Drag and drop UIViewController from object library on to Storyboard. Now to setup relationship between this View Controller and the ViewController embeded in Navigation Controller you need to create a Push segue. This can be done by selecting the Prototype cell then press Control and drag drop to the new ViewController. Select the type of Segue as Push as shown below.

After creating the push segue relationship, you should notice that the newly added ViewController has a navigation bar at the top. Now if you build and run the project, you should be able to navigate between the ViewControllers (Did you notice the Colours button?).

Change background colour

We need to add the functionality that when a user taps any colour in the Main ViewContorller, the background colour of the child ViewController will be set to the selected colour.

Add a new file and choose the template for your new file as Cocoa Touch Class.

Make the new class as Subclass of UIViewController and provide the name as ColourViewController.swift

Using the Interface builder, set the class as ColourViewController (Identity Inspector) and also provide the Storyboard ID as ColourViewController

Now add colour property to the ColourViewController and this will hold enum value of the selected colour in the ManiViewController.

[code language=”swift”]
var colour: Int?[/code]

And in the viewDidLoad function add the following code snippet.

[code language=”swift”]override func viewDidLoad() {
super.viewDidLoad()

if let colour = colour {
let hex:Colours = Colours.getEnumFromSelectedValue(colour)
view.backgroundColor = Colours.getUIColorFromHex(hex.rawValue, alpha: 1.0)

navigationItem.title = hex.getDisplayName()
}
}[/code]

The above code snippet retrieves the colour enum and corresponding UIColor by passing the color hex code. This colour is then set as the background colour of the current view. Also the display name of the colour is set as the title for the navigation bar.

Add prepareForSegue funciton

Navigate to back to the ViewController.swift file and add the following prepareForSegue funciton.

[code language=”swift”]//MARK:- PrepareForSegue

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == “Colour” {
let colourViewController:ColourViewController = segue.destinationViewController as! ColourViewController
let selectedRow = tableView.indexPathForSelectedRow()?.row
colourViewController.colour = selectedRow
}
}[/code]

The above function instantiates the ColourViewContoller from segue.destinationViewController and sets the selected colour form the tableView to the colour property of the ColourViewController.

Now if you build and run the app, you should see the list of colours and on selecting any colour shoud take you to the Child ViewController and setting the background colour to the selected colour. Also you should be able to navigate back by tapping the Colours button in the navigation bar.

Adding toolbars to Navigation Controllers

Let us see how to programmatically add toolbars to a ViewController embeded in a Navigation Controller. Open ViewController.swift for editing and add the following functions

[code language=”swift”]//MARK:- Add toolbar items
func addToolBarItems() {

let segue = UIBarButtonItem(title: “Segue”, style: .Plain, target: self, action: “segueCall”)
let nonSegue = UIBarButtonItem(title: “Non Segue”, style: .Plain, target: self, action: “nonSegueCall”)
let seperator = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)

var items = [segue,seperator,nonSegue]

self.setToolbarItems(items as [AnyObject], animated: true)
navigationController?.setToolbarHidden(false, animated: true)
}

//MARK:- Segue call
func segueCall(){
performSegueWithIdentifier(“Colour”, sender: self)
}

//MARK:- Non Segue call
func nonSegueCall() {
let childViewController = storyboard?.instantiateViewControllerWithIdentifier(“ColourViewController”) as! ColourViewController
navigationController?.pushViewController(childViewController, animated: true)
}[/code]

addToolBarItems funciton creates a UIBarButtonItems along with a separator (flexible space). These array of UIBarButtonItems are then added to the ViewController using setToolBarItems function. Also we need to unhide the toolbar in navigation contoller using setToolbarHidden function.

The segueCall function shows how to programmatically call segue transition using performSegueWithIdentifier. The nonSegueCall function is used for ViewController transitions inside navigation controller but without using a Segue. Build and Run the app should now display toolbar at bottom of the ViewController.

Finally we will see how to programmatically dismiss ViewController embeded in navigation controller. Open ColourViewController.swift for editing and add the following piece of code which add a toolbar item and dismiss the ViewController by calling navigationController?.popViewControllerAnimated(true)

[code language=”swift”]//MARK:- Add toolbar items

func addToolBarItems() {

let nonSegue = UIBarButtonItem(title: “Non Segue”, style: .Plain, target: self, action: “nonSegueCall”)
var items = [nonSegue]

self.setToolbarItems(items as [AnyObject], animated: true)
}

func nonSegueCall() {
navigationController?.popViewControllerAnimated(true)
}[/code]

Tapping on Non Segue should dismiss the Child ViewController and take you to the main ViewController.

Download the source code from here.

Filed Under: ios, Xcode Tagged With: NavigationController, Segue, Toolbars

Swift Demo – Add Progress Bar

June 24, 2015 By Ravi Shankar Leave a Comment

In this short tutorial, we will see the steps required to add UIProgressView to a Swift IOS Project.

UIProgressView and UILabel showing the current progress will be added programmatically to the View Controller. Create a Single View Application and navigate to ViewController.swift file.

Add UIProgressView and UILabel

Add the following code snippet below the class definition. This code snippet adds variables for UILabel and UIProgressView.

[code language=”swift”] var progressView: UIProgressView?
var progressLabel: UILabel?
[/code]

Now add the following function which initialises and adds UIProgressView and UILabel to the view.

[code language=”swift”]//MARK:- Controls
func addControls() {
// Create Progress View Control
progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.Default)
progressView?.center = self.view.center
view.addSubview(progressView!)

// Add Label
progressLabel = UILabel()
let frame = CGRectMake(view.center.x – 25, view.center.y – 100, 100, 50)
progressLabel?.frame = frame
view.addSubview(progressLabel!)
}
[/code]

ProgressView style can be set to Default or Bar type. And UILabel needs to be appear just above the ProgressView hence we added an offset from view center.

Add GestureRecogonizers

This demo starts and resets the progress on single and double tap gesture event. The following code snippet adds single and double tap gesture recognisers to the view. This also specifies the function that needs to be called when user does a single or double tap.

[code language=”swift”]func addGestures() {
// Add Single Tap and Doube Tap Gestures
let tap = UITapGestureRecognizer(target: self, action: "handleTap:")
tap.numberOfTapsRequired = 1

let doubleTap = UITapGestureRecognizer(target: self, action: "handleDoubleTap:")
doubleTap.numberOfTapsRequired = 2

view.addGestureRecognizer(tap)
view.addGestureRecognizer(doubleTap)
tap.requireGestureRecognizerToFail(doubleTap)
}
[/code]

Now add the required functions for the gesture recogonizer events.

[code language=”swift”]// Start Progress View
func handleTap(sender: UITapGestureRecognizer) {
if sender.state == .Ended {
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateProgress", userInfo: nil, repeats: true)
}
}
//MARK:- Double Tap
// Reset Progress View
func handleDoubleTap(sender: UITapGestureRecognizer) {
if sender.state == .Ended {
progressView?.progress = 0.0
progressLabel?.text = "0 %"
timer?.invalidate()
}
}[/code]

Display Progress

The actual progress will be displayed by the following piece of code in the updateProgress function. You can change progress interval by setting appropriate value to progress property of UIProgressView.

[code language=”swift”]//MARK:- Increment Progress
func updateProgress() {
progressView?.progress += 0.05
let progressValue = self.progressView?.progress
progressLabel?.text = "\(progressValue! * 100) %"
}[/code]

Finally we need to add the addControls and addGestures to the viewDidLoad method.

[code language=”swift”]override func viewDidLoad() {
super.viewDidLoad()
addControls()
addGestures()
}[/code]

Download source code from here (SwiftDemo – ProgressView)

Filed Under: ios, Xcode Tagged With: Gestures, UIProgressView

Create new Test Target in Xcode

June 22, 2015 By Ravi Shankar Leave a Comment

Listed below are the steps to add test target for an existing iOS Projects (iOS 6.0 and older).

Click File menu -> New and Select Target from the menu list.

Then select Cocoa Touch Testing Bundle under iOS -> Other template section.

Enter product name for the new target and other details and click FInish.

Now you should be able to see the newly added test target under Project Navigator and Test Navigator.

Filed Under: Xcode Tagged With: iOS Projects, Test Driven Development, Test Target

DatePicker Demo in Swift

June 17, 2015 By Ravi Shankar 6 Comments

In this short tutorial, we are going to see the steps required use DatePicker in a iOS / Swift project. This demo is done by adding the DatePicker controls to Interface Builder and not programmatically.

Date Picker Mode

Date Picker control allow developers to specify the mode such as Date, Time, Date and Time and Count Down Timer. Listed below are the screenshots of each Date Picker mode.

Date Picker (Mode – Time)

Date Picker Mode set to time

Date Picker (Mode – Date)

Date Picker Mode set to Date

Date Picker (Mode – Date and Time)

Date and Time mode set for Date Picker

Using the Date and Time mode does not provide option to pick year. Hence in this demo we are going to use two date picker controls, one for date and another for time.

Add ViewContoller and Controls

Add a View Controller (or use existing ViewController) to storyboard then drag and drop 2 date picker controls to the View Controller. Also add a UILabel for displaying the selected date and time values. For the first Date Picker set the mode to Date and for the second as Time.

Add DatePickerController class

Now add a new file to the project and choose the template as Cocoa Touch class. Provde the name for your class file as DatePickerController. Add the following lines of code that adds IBOutlets to the ViewController

[code language=”swift”]@IBOutlet var datePicker:UIDatePicker!
@IBOutlet var timePicker:UIDatePicker!
@IBOutlet var dateTimeDisplay:UILabel![/code]

Select the ViewController in the Storyboard and set the class in the Identity Inspector to DatePickerController. Now click Show Assistant Editor then Control + drag and drop date picker to class file. Select connect as Action and provide the name for the function as datePickerChanged.

Now you should see the following function added to your class file.

[code language=”swift”]
@IBAction func datePickerChanged(sender: AnyObject) {
}[/code]

Repeat this exercise for the TimePicker (second date picker control) with function name as timePickerChanged.

[code language=”swift”]@IBAction func timePickerChanged(sender: AnyObject) {
}[/code]

Also make sure to connect all the IBOutlets from the class file to the corresponding controls in View Controller.

Set Date and Time

Add the following piece of Date Formatter code just below the IBOutlets definition. We are using two instance of NSDateFormatter to specify the date and time style for each date picker controls.

[code language=”swift”]let dateFormatter = NSDateFormatter()
let timeFormatter = NSDateFormatter()[/code]

Add the following function that formats the date and time and assigns the value to UILabel.

[code language=”swift”]//MARK:- Date and time
func setDateAndTime() {
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
dateTimeDisplay.text = dateFormatter.stringFromDate(datePicker.date) + ” ” + timeFormatter.stringFromDate(timePicker.date)
}[/code]

Add the function call to the date picker’s Value Changed methods.

[code language=”swift”]@IBAction func datePickerChanged(sender: AnyObject) {
setDateAndTime()
}
@IBAction func timePickerChanged(sender: AnyObject) {
setDateAndTime()
}[/code]

Download the source code from here (SwiftDemo -> DatePicker)

Filed Under: ios, Programming, Xcode Tagged With: DatePicker, Swift

Memory management in Swift

June 7, 2015 By Ravi Shankar Leave a Comment

Memory management in Swift is done by Automatic Reference Counting or ARC. Whenever a variables holds an instance of a object the memory count for that object increases by 1. And when variable become out of scope or set to nil, the memory count decreases 1.

[code language=”swift”]class Teacher {
var name: String?
var course: String?

init (name: String, course: String) {
self.name = name
self.course = course
println("Reference count increased by 1")
}

deinit{
println("Reference count decreased by 1")
}
}

let teacher1 = Teacher(name: "Ravi", course: "Swift")

func createTeacher() {
let teacher2 = Teacher(name: "John", course: "Java")
}

createTeacher()[/code]

 

In the above example, we are creating two instances of Teacher class and storing it in variables teacher1 and teacher2. Since teacher2 variable is created within the function, it becomes out of scope after the function call. You should be able to observe the two init messages and one deinit (teacher2) message in console log. This should give you some idea on how reference counting works in Swift.

Increasing and decreasing of reference count are automatically handled by ARC but problem occurs when we have a strong reference cycle. A strong reference cycle refers to cyclic relationship between the objects.

[code language=”swift”]class Teacher {
var name:String?
var course:String?
var student: Student?

init(name: String, course:String) {
self.name = name
self.course = course

println("Reference count of Teacher increases by 1")
}

deinit {
println("Reference count of Teacher decreases by 1")
}
}

class Student {
var name:String?
var mentor: Teacher?

init(name: String, course:String) {
self.name = name

println("Reference count of Student increases by 1")
}

deinit {
println("Reference count of Student decreases by 1")
}
}

func createInstance() {
let teacher = Teacher(name: "Jason", course: "Swift")
let student = Student(name: "Adam", course: "Swift")
teacher.student = student
student.mentor = teacher
}

createInstance()[/code]

In the above code snippet, Teacher and Sudent classes have a strong reference cycle and both student and teacher instances remain in memory even after the end of function call. A strong reference cycle can be avoided by declaring any one of the instance as weak or unowned

[code language=”swift”]weak var student: Student?
[/code]

You can also unown the reference when you know the reference cannot be nil

[code language=”swift”]unowned var mentor: Teacher[/code]

Download playground file from gitHub (Memory Management)

Filed Under: ios, iPad, iPhone, Xcode Tagged With: ARC, iPad, Memory Management, Xcode

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

    1. Pages:
    2. «
    3. 1
    4. 2
    5. 3
    6. 4
    7. 5
    8. 6
    9. 7
    10. 8
    11. »
    « 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