• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

ios

SplitViewController example in Swift

April 1, 2015 By Ravi Shankar 4 Comments

This is a beginners tutorial on SplitViewController using Interface builder with programming language as Swift. There are also some good articles available on SplitViewController, check them out as well – nhipster and whoisryannystrom.

Create a new Single View Application.

201503290525.jpg

Choose Language option as Swift and provide a product name.

201504011302.jpg

Navigate to Main.Storyboard and select default View Controller and delete it.

201504011304.jpg

Add a Split View Controller from the object library to the interface builder.

201504011305.jpg

Using Attributes Inspector make Split View Controller as the Initial View Controller

201504011307.jpg
Select View Controller in the Interface builder then click Editor menu and select Navigation Controller under Embed In menu option.

201504011308.jpg

Rename ViewController.swift to DetailViewController.swift and change the class name as well.

201504011317.jpg

Navigate to Interface builder and set the class name for ViewController scene to DetailViewController

201504011321.jpg

Now Control + drag and drop TablevIew Prototype cell to NavigationController (DetailViewController) and select segue as show detail. Also set the identifier for the Storyboard Segue as “ShowDetailIdentifier“

201504011323.jpg

201504011326.jpg

Navigate to RootViewController (TableViewController) Provide the Identifier as CellIdentifier for the Prototype Cells.

201504011325.jpg

Right click on the Project Navigator, select New File and Choose the template as Cocoa Touch Class

201504011331.jpg

In the next screen, select subclass as UIViewController and provide a name as SplitViewController

201504011332.jpg

After creating the file, edit SplitViewController subclass to UISplitViewController. Then add the following line to the viewDidLoad method.

  splitViewController?.preferredDisplayMode = .PrimaryOverlay

The above line is to keep the PrimaryViewController (TableViewController) on top of SecondaryViewController (DetailViewController). You can change this behaviour by setting other types, check the documentation for more details.

201504011407.jpg

Now add the PrimaryViewController (TableViewController) by right clicking and selecting New File. Select Cocoa Touch class and in the subclass field pick UITableViewController. Provide the the name for the TableViewController ListTableViewController.

201504011409.jpg

Set the class name for the RootViewController (TableViewController) to the newly created class, ListTableViewController.

201504011424.jpg

Navigate to DetailViewController in the Interface builder, add a label and make it horizontally and vertically centred.

201504011524.jpg

Then add a new IBOutlet in DetailViewController and connect the Outlet to the label in interface builder.

  @IBOutlet var numberLabel:UILabel?

Also add property of type Int and the value for this property will be set during the segue transition.

var selectedIndex:Int = 1

Make changes to the viewDidLoad method, to set the value for the label and to add back button to the navigation bar.

override func viewDidLoad() {

super.viewDidLoad()

  

numberLabel?.text = “\(selectedIndex)“

  

// add back button to the navigation bar.

  

if splitViewController?.respondsToSelector(“displayModeButtonItem”) == true {

navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem()

navigationItem.leftItemsSupplementBackButton = true

}

}

In the ListTableViewController, add the following code that sets the datasource.

  let names = [“One”,“Two”,“Three”,“Four”,“Five”,“Six”,“Seven”,“Eight”,“Nine”,“Ten”] (class level declaration)

  // MARK: – Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

return 1

}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return names.count

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

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

   cell.textLabel?.text = names[indexPath.row]

return cell

}

Then make changes to the prepareForSegue method to navigate to DetailViewController after setting the selectedIndex property

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

if (segue.identifier == “ShowDetailIdentifier”) {

var detail: DetailViewController

if let navigationController = segue.destinationViewController as? UINavigationController {

detail = navigationController.topViewController as DetailViewController

} else {

detail = segue.destinationViewController as DetailViewController

}

  

if let path = tableView.indexPathForSelectedRow() {

detail.selectedIndex = path.row + 1

}

}

}

201504011556.jpg

Download the source from here.

Filed Under: ios, iPad, iPhone, Programming, Xcode Tagged With: Demo, iPad, UISplitViewController, Xcode

payworks SDK integration in Swift

March 26, 2015 By Ravi Shankar Leave a Comment

payworks mPOS helps app developers to integrate their App with card reader. In this tutorial, we will see a sample app that integrates payworks mPOS using Swift.

Download the source code from github

Select New Project and choose Single View Application from the template.

201503260807.jpg

In the Project Options window, provide a product name and make sure to select Language as Swift. Click Next and Save the project.

201503260812.jpg

In the Project Navigator, select Main.storyboard and unmark check box “Use Size Classes” in the File Inspector. Then click Disable Size Classes button as this app is only designed for iPhone

201503260825.jpg

UI Design

Design the user interface as shown below.

  • Label to shown caption as Amount
  • TextField for entering the amount
  • Button to Charge Amount.
  • Label to display the status message.

201503260840.jpg

Just to reflect the purpose of this little app, let us rename the ViewController.Swift to ChargeViewController.swift. Make the corresponding changes to Class name as well in Identity Inspector.

Integrate mPOS SDK

We are going to add mPOS SDK to this project using CocoaPods by following the instructions here.

Close your Xcode project, launch Terminal window and and navigate to project folder.

201503260927.jpg

Create a new Podfile with the following statements

201503260929.jpg

Doing a pod install should download the mPOS SDK’s to your project folder.

201503260936.jpg

Now navigate to your project folder and open the file with extension as .xcworkspace. The Pods folder in the project navigator should contain the mPOS framework.

201503260956.jpg

Objective-C Bridging

We need to create a bridge file to call the objective-c related framework files in our Swift app. The easiest way to do this is to create new Objective-C file in your project.

Right click on your project folder, select New File.

201503260959.jpg

In the Choose a template screen, select Objective-C and click Next.

201503261005.jpg

Provide a name for the Objective-C file and save the file.

201503261007.jpg

Now you will prompted whether you would like to configure an Objective-C bridging header. Click Yes to create the bridging header file.

201503261007.jpg

As the header file is created, we do not need the temp objective-c file, you can delete this file.

201503261021.jpg

Navigate to Bridging-Header file in Project navigator and the following lines.

@import Foundation;

#import

Now you can make sure every thing works fine by doing a build. Also make sure to add the additional steps as mentioned in the instruction page for Miura Readers. Navigate to info.plist and add supported external accessory protocols and Required background modes keys.
201503261032.jpg
mPOS integration
Create two IBOutlets, one for TextField and another for Message Label.

  @IBOutlet weak var amountTxtField: UITextField!

@IBOutlet weak var messageLabel: UILabel!

  

Use the connection inspector to connect the IBOutlets with the controls.

201503261037.jpg

In order to connect with mPOS SDK, you need to register and get the merchant credentials, You can do this by registering here. After receiving the credentials create two constants to hold the identifier and secret key.

  let MERCHANT_IDENTIFIER = “YOUR_MERCHANT_IDENTIFIER”

let MERCHANT_SECRET_KEY = “YOUR_SECRET_KEY”

201503261049.jpg
Now add the following IBAction method to ChangeViewController.swift and connect the IBAction with the button.

  @IBAction func chargeCard(sender: UIButton) {

  

let amount:NSDecimalNumber = NSDecimalNumber(string: self.amountTxtField.text)

  

let transactionProvider:MPTransactionProvider = MPMpos .transactionProviderForMode( MPProviderMode.MOCK, merchantIdentifier: MERCHANT_IDENTIFIER, merchantSecretKey: MERCHANT_SECRET_KEY)

  

let template: MPTransactionTemplate = transactionProvider.chargeTransactionTemplateWithAmount(amount, currency: MPCurrency.EUR, subject: “subject”, customIdentifier: “customIdentifier”)

  

let paymentProcess:MPPaymentProcess = transactionProvider.startPaymentWithTemplate(template, usingAccessory: MPAccessoryFamily.Mock, registered: { (let paymentProcess:MPPaymentProcess!, let transaction:MPTransaction!) -> Void in

  

}, statusChanged: { (let paymentProcess:MPPaymentProcess!, let transaction:MPTransaction!, let paymentProcessDetails:MPPaymentProcessDetails!) -> Void in

  

self.messageLabel.text = self.formatMessage(paymentProcessDetails.information)

  

}, actionRequired: { (let paymentProcess:MPPaymentProcess!, let transaction:MPTransaction!, let transactionAction:MPTransactionAction, let transactionActionSupport:MPTransactionActionSupport!) -> Void in

  

}) {(let paymentProcess:MPPaymentProcess!, let transaction:MPTransaction!, let paymentProcessDetails:MPPaymentProcessDetails!) -> Void in

  

self.messageLabel.text = self.formatMessage(paymentProcessDetails.information)

}

}

  

func formatMessage(information:AnyObject) -> String {

let temp = (information[0] as NSString) + “\n”

return temp + (information[1] as NSString)

}

Since I don’t have a real reader to try this demo, I have used Mock mode for the transaction provider and payment process
  let transactionProvider:MPTransactionProvider = MPMpos .transactionProviderForMode( MPProviderMode.MOCK, merchantIdentifier: MERCHANT_IDENTIFIER, merchantSecretKey: MERCHANT_SECRET_KEY)

  let paymentProcess:MPPaymentProcess = transactionProvider.startPaymentWithTemplate(template, usingAccessory: MPAccessoryFamily.Mock, registered:

Now you are good to try this demo by entering an amount and tap the Pay button. The trisection status will be displayed in the message label.

201503261058.jpg
You can also test your solution by entering different amount as mentioned in the test page.
201503261101.jpg
Download the source code from github

Filed Under: Apple, ios, iPhone, Mac, Programming Tagged With: Apple, integration, payowrks, Swift

Swift Interview Questions

March 7, 2015 By Ravi Shankar Leave a Comment

Listed below are some of topics to be familiar before attending an iOS//Swift interviews. These are very trivial questions but in future this space will updated with more scenario based questions

  • What are the different app states?
  • What is JSON?
  • What do you mean by REST?
  • Difference between class and struct?
  • What are Optionals?
  • Difference between Optional Chaining and Optional Binding?
  • why do we have to use UICollectionViewFlowLayout?
  • Difference between frame and bounds?
  • What is NSCoder class used for? 
  • What is NSOperationQueue and when should we use it?
  • What are extensions? Explain the difference between extension and subclassing?
  • Difference between delegates and NSNotifications?
  • What are protocols in Swift?
  • What is interpolation?
  • Explain type inference in Swift?
  • Difference between Auto Layout and Adaptive Layout?
  • Is possible to use an Objective-C framework in Swift? 
  • Explain the different life cycle of UIViewController?
  • Difference between xib’s and Storyboards.
  • Explain MVC?
  • What is MVVM?
  • what is an app bundle?
  • Write a sample code for Singleton design pattern?
  • What is difference between Unit tests and UI Test in Xcode?
  • Can you make updates to UI from a background thread? 
  • Difference between let and var keywords in Swift?
  • What are generics? Can you write generics example code?
  • Difference between designated and convenience initialiser?

Filed Under: Interview Questions, ios, Swift

Debugging Swift App in Xcode

February 17, 2015 By Ravi Shankar 1 Comment

Any beginner iOS developer should be aware of the NSLog statement. This is quite frequently used to debug Objective-C programs. In Swift you can use println or print statement instead of NSLog to write the debug information to the console log.

[code language=”swift”]var primeFlag:Bool = true
println("input number is \(number)")
if ((number == 2) || (number == 3)) {
return primeFlag
}
[/code]

 

This will write the following message in the console log.

input number is 5

But debugging a large app using println statement will be a time consuming process, instead you can use Xcode built-in features for debugging.

Breakpoint

 

Xcode users can place breakpoint at a specific statement and when the program execution reaches that line it pauses the execution. The breakpoint allows users to examine the value of variables at that specific context.

201502160926.jpg

Like any other IDE, Xcode provides option to Step Into, Step Out, Step Over and Continue option.

201502160929.jpg

Exception Breakpoint

When your app crashes and you want the app the stop at the line of statement that causes the crash then you can use Exception breakpoint. Click Debug menu and select Create Exception Breakpoint from the menu list.

201502161005.jpg

Conditional breakpoint

If you want to pause the execution using a breakpoint when a condition is met then you can use conditional breakpoint.

201502162238.jpg

Right click a breakpoint and select Edit BreakPoint from the list. Then add the add the condition for the breakpoint. In the below screenshot, when index reaches 251 the breakpoint will be activated.

201502170549.jpg

Symbolic breakpoint

Symbolic breakpoint pauses the program execution when it reaches the specified method. For example you want to pause the program execution in all the viewDidLoad methods then you can specify that using Symbolic breakpoint.

Debug menu -> Breakpoints -> Create Symbolic Breakpoint

201502170555.jpg

Enter the method name in symbol field and to target only specific module instead of all viewDidLoad methods you can enter the module name as well.

201502170820.jpg

Watch Point

When you want to pause the app execution whenever the value of a variable changes then you can use watch point. You can add a watch point by selecting variable and picking Watch option from the context menu.

201502170829.jpg

Breakpoint navigator

Xcode Breakpoint navigator will show the list of breakpoints that are currently active in your project.

201502170836.jpg

And you can remove all and selected breakpoints by right clicking on the Breakpoint navigator and selecting Delete Breakpoints option.

201502170838.jpg

Enable sound

Another useful feature which is available as part of Xcode debugging tool is to play sound when a breakpoint condition is met. This is quite useful when you have Xcode debugging in the background and want to let you know when the condition is met by playing the sound.

201502170845.jpg

To specify the condition, click on the Action drop down and select Sound from the list. Then add the notification sound that needs to played when the condition is met.

201502170846.jpg

Filed Under: Apple, ios, Programming, Xcode Tagged With: Apple, debugging, Swift, Xcode

Test Driven Development in Swift

February 9, 2015 By Ravi Shankar Leave a Comment

Here is a beginner tutorial on TDD in Swift by writing a program that checks for a prime number. Let us start by creating a new project, selecting template as Single View Application. Though we won’t be adding anything to the storyboard as we will focus only on the business logic.

201502082101.jpg

201502082103.jpg

After creating the project, the project navigator should have the following structure.

201502082104.jpg

from wikipedia

A prime number is a natural number greater than 1 that no positive divisors other than 1 and itself. – 2,3,5,7,11,13 ….

So now that we know the first prime number is 2, let us add a unit test that checks if number 2 is a prime number. We are going to have a new class called Util that will have the required function to check if a number is prime number. Before creating a Util class, create unit test class called TestsForUtil.swift.

201502082115.jpg

Select the template as Test Case Class and go with the default settings. Now you should see the newly added class as part of the project navigator under CheckForPrimeTests.

201502082117.jpg

As we don’t need CheckForPrimeTests.Swift, we can delete the file. And on opening TestsForSwift.swift, you should notice the following default test methods. setup(), tearDown(), testExampe(), testPerformanceExample(). In this demo, we are not going to use any of these methods and so you can remove them as well.

Let us add our first unit test that checks if number 2 is prime number. Add the following method,

func testTwoIsPrime() {

let number:Int = 2;

XCTAssertTrue(Util().isPrime(number), “2 is a prime number”);

}

You should see use of Unresolved identifier “Util as we are yet to add the class.

In TDD we write the tests first and then add the required functionality. Test Driven Development will ensure that you add only required code to pass your tests.

What this test function does is, it calls isPrime function in Util and receives if a boolean on whether the entered number is prime number. This unit test will show Pass status when the value received from isPrime is true.

Now add a Swift file with name as Util and make sure to select CheckForPrimeTests under Targets. This would ensure you can call functions written in Util class

201502082151.jpg

201502082152.jpg

Create a public class with name as Util and add function isPrime as shown below.

public class Util {

  

func isPrime(number:Int) -> Bool {

return number == 2

}

}

All we are doing here is to make sure the function validates number 2. Now executing unit test should show a green tick mark as shown below.

201502090829.jpg

Navigate back to TestsForUtil.swift and add second tests which checks for number 3.

  func testThreeIsPrime() {

let number:Int = 3;

XCTAssertTrue(Util().isPrime(number), “3 is a prime number”);

}

On executing this test you should notice failure message as we have hard coded isPrime function to work only for 2.

201502090831.jpg

And to make this test pass, we are going to check for 2 and 3 in isPrime function.

  func isPrime(number:Int) -> Bool {

return (number == 2) || (number == 3)

}

Let us add the unit test that checks for 4 which is not a prime number.

  func testFourIsPrime() {

let number:Int = 4;

XCTAssertFalse(Util().isPrime(number), “4 is not a prime number”);

}

We have used XCTAssertFalse as we are expecting isPrime to return false. This test would pass with out making any changes to isPrime function.

201502090838.jpg

Now let us add out next test case that checks for number 11.

  func testElevenIsPrime() {

let number:Int = 11;

XCTAssertTrue(Util().isPrime(number), “11 is a prime number”);

}

201502090841.jpg

We need to make changes to isPrime function so it returns true for number 11. But we cannot just keeping on hardcoding the numbers. So let us change the logic to handle all the prime numbers.

  func isPrime(number:Int) -> Bool {

  

var primeFlag:Bool = true

  

if ((number == 2) || (number == 3)) {

return primeFlag

}

  

if (number > 3) {

  

for index in 2…number-1 {

if (number % index == 0) {

primeFlag = false

break

}

}

}

  

return primeFlag

}

The above function would validate all prime and not a prime numbers and test written for number 11 should pass. Now you can write some tests for prime and not a prime number. For not a prime number make sure to use XCTAssertFalse.

  func testThirtyOneIsPrime() {

let number:Int = 31;

XCTAssertTrue(Util().isPrime(number), “31 is a prime number”);

}

  

func testFiftyIsPrime() {

let number:Int = 50;

XCTAssertFalse(Util().isPrime(number), “50 is not a prime number”);

}

Now let us check this logic for a negative number say -1. Negative numbers are not prime number so isPrime function should handle this. But this test would fail as we don’t have any check for negative numbers.

  func testMinusOneIsPrime() {

let number:Int = –1;

XCTAssertFalse(Util().isPrime(number), “-1 is not a prime number”);

}

Making a minor modifications to isPrime function should pass the test.

func isPrime(number:Int) -> Bool {

  

var primeFlag:Bool = true

  

if ((number == 2) || (number == 3)) {

return primeFlag

}

  

if (number > 3) {

  

for index in 2…number-1 {

if (number % index == 0) {

primeFlag = false

break

}

}

} else {

primeFlag = false

}

  

return primeFlag

}

And the test navigator in Xcode should show status for all your tests.

201502090920.jpg

The logic used in isPrime function can be improved and you can probably do that as your exercise. And make sure all the unit tests have green tick mark after changing isPrime function.

Download the source code from here.

Filed Under: Develop, ios, Programming, Xcode Tagged With: Swift, TDD, Test Driven Development, Xcode

Enum in Swift

January 13, 2015 By Ravi Shankar Leave a Comment

Enum group of 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.

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

}

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

let currentMonth = Month.May

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

let currentMonth:Month = .May

 

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

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”

}

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

let currentMonth:Month = .May

currentMonth.rawValue

Enum with Associated Value

 

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

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”)

}

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.

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()

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 and 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.

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()

 

Filed Under: Apple, Develop, ios, iPad, iPhone, Programming Tagged With: Apple, Enum, Initializer, iPad, Member Function, RawValue

Tuples in Swift

January 13, 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

let employee = (103, “Deepak”)

employee.0

employee.1

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.

let employee = (id:103, name:“Deepak”)

employee.id

employee.name

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

let employee:(id:Int, name:String) = (102, “Deepak”)

employee.id

employee.name

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.

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”)

}

Filed Under: Apple, ios, iPad, iPhone, Programming Tagged With: Apple, iPad, Switch, Tuples

Remove Apple Mach-O Linker directory not found

November 23, 2014 By Ravi Shankar Leave a Comment

Listed below are the steps to remove Apple Mach-O linker warning directory not found warning message.

201411232014.jpg

1. Navigate to Project Navigator, select the Project then navigate to Build Settings.

201411232016.jpg

2. Under Build Settings, scroll down to Search Paths and double click on Library Search Paths.

201411232021.jpg

3. Select the missing folder paths and remove them using “-“ sign.

201411232028.jpg

Filed Under: Develop, ios, Xcode Tagged With: 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