• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

Develop

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

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

Integrating Stripe in Swift for iOS development

September 2, 2014 By Ravi Shankar 12 Comments

Stripe is payment gateway that can be integrated with any website and mobile apps. In this tutorial we will see a quick and simple integration of Stripe in Swift for iOS development using Stripe documentation for iOS.

201409021233.jpg

This hands on tutorial will help you to familiarise yourself in

  • Validating and creating token using Stripe IOS SDK
  • Installing third party library using Cocoa-pods (Stripe)
  • Calling Objective-C framework in Swift (Objective-C Bridging Headers settings)

Click File menu and select New -> Project

201409021049.jpg

Select Single View Application as the template for the project.

201409021050.jpg

Provide a name for your project and select the language as Swift.

201409021110.jpg

Now close the project in Xcode and launch terminal window.

Setup Stripe using Cocoa-pods

Run the following commands on your terminal window to install Stripe.

[code language=”plain”]sudo gem install cocoapods
pod init[/code]

Edit Podfile under project directory and add pod ‘Stripe’ then execute the below command in Terminal window.

[code language=”plain”]pod install[/code]

Navigate to the project folder and launch the file with extension as workspace. Now you should see the Stripe frameworks included under Pods directory along with your default project files.

201409021131.jpg

Write code to integrate Stripe

Edit ViewController.swift and add the following IBOutlet variable for the button.

[code language=”swift”]@IBOutlet var saveButton: UIButton![/code]

Now add the following variable declaration to ViewController.swift file to hold the instance of STPView class.

[code language=”swift”]var stripeView: STPView = STPView()[/code]

Since the Stripe framework has been written in Objective-C, we need to make sure to add the implementation file as part of the Objective-C bridging Headers under Build Settings.

Select Project folder and navigate to Build Settings. Then use the search field to locate to Objective-C Bridging Header setting.

201409021153.jpg

Then drag and drop the STPView.m file to Object-C Bridging Header section.

201409021155.jpg201409021156.jpg

Update the viewDidLoad function and add the following Stripe integration code. Make sure the ViewController class conforms to STPViewDelegate protocol

[code language=”swift”]class ViewController: UIViewController, STPViewDelegate{
override func viewDidLoad() {
super.viewDidLoad()
stripeView = STPView(frame: CGRectMake(15, 20, 290, 55), andKey: )
stripeView.delegate = self
view.addSubview(stripeView)
saveButton.enabled = false
}
}[/code]

 

The above lines of code will add the Stripe control that accepts credit card number, expiry date and code. The save button is by default disabled and will be enabled only after entering valid credit card number. Implement the following function that will be triggered after entering the card details. The boolean parameter in the function will indicate whether the user has entered a valid card information. Based on this value, the save button is enabled or disabled.

[code language=”swift”]func stripeView(view: STPView!, withCard card: PKCard!, isValid valid: Bool) {
if (valid) {
saveButton.enabled = true
} else {
saveButton.enabled = false
}
}[/code]

Add the following IBAction function which will be called on tap of the button. We are using STPView’s createToken function to generate token and a successful token will be written to the console window.

[code language=”swift”]@IBAction func saveButton(sender: AnyObject) {
stripeView.createToken { (stpToken, error) -> Void in
if (error != nil) {
println(error)
} else {
println(stpToken)
}
}[/code]

Navigate to Main.storyboard and add UIButton from object library to ViewController. Centre align the button both horizontally and vertically to the View Controller.

201409021138.jpg

Then use Connection Inspector to connect the button to IBOutlet variable and saveButton function to Tap Up Inside event of the button.

201409021228.jpg

Now build and run the project on simulator and you can use dummy card number 4242 4242 4242 4242 to test your implementation. For more details refer to Stripe Testing Documentation.

Sample Output

[code language=”plain”]Successful token – tok_14YBF42eZvKYlo2CoZtuO3Md (test mode)

Error message – Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo=0x7f9b7147b4a0 {NSUnderlyingError=0x7f9b71786ca0 "The Internet connection appears to be offline.", NSErrorFailingURLStringKey=https://pk_test_6pRNASCoBOKtIshFeQd4XMUh:@api.stripe.com/v1/tokens, NSErrorFailingURLKey=https://pk_test_6pRNASCoBOKtIshFeQd4XMUh:@api.stripe.com/v1/tokens, _kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8, NSLocalizedDescription=The Internet connection appears to be offline.}[/code]

Download Demo Project from GitHub

Filed Under: Develop, ios, iPhone, Programming Tagged With: Stripe, Swift

Quotes app – Simple page based application in Swift

August 13, 2014 By Ravi Shankar 8 Comments

This is a very basic tutorial on how to create a simple page based app in Swift. We are going to use Page Based Application project template for displaying quotes in different pages.

201408131144.jpg201408131148.jpg

 

Create Page-Based Application in Swift

Click Xcode File menu, navigate to New and select Project from sub menu list.

201408131151.jpg

Select Page-Based Application in template screen and click Next button.

201408131152.jpg

In the Project Options screen, provide a name for your project and select language as Swift. Then click Next button and save your project.

201408131154.jpg

This should create a default page based application in Swift with the following project structure.

201408131156.jpg

Run the project on Simulator should display a page based app displaying names of months. When you tap or swipe the screen, next page should be displayed.

201408131159.jpg

Modifying the default Page-based application

We are going to modify the existing app to display quotes instead of months. The default project follows MVC pattern for retrieving and displaying the data. RootViewController.swift does the controller part, DataViewController.swift/Storyboard is used for displaying Views and ModelViewController.swift provides the data.

Let us first start with the changes to Storyboard. Navigate to Main.storyboard, select and delete the View and Label under Data View Controller.

201408131217.jpg

Set the background colour of the View to Purple using Attributes Inspector.

201408131220.jpg

Drag and drop a UILabel from Object library on to View Controller. Make sure to Centre align the label both vertically and horizontally.

201408131231.jpg

Use the Attributes Inspector to set the colour, alignment and Font for UILabel’s Text. Then change the number of lines displayed in UILabel to 3. Next use the align option in Interface builder to add the Horizontal and Vertical Center constraints (select Use Current Canvas Value)

201408131246.jpg

Click Connection Inspector and connect dataLabel to the newly added UILabel. dataLabel property was already added to the DataViewController.swift to display month name.

201408131250.jpg

Make changes to ModelViewController

Now we need to provide the required data for the display. Click ModelViewController.swift and change the pageData variable in to a constant and add array of four quotes as shown below.

[code language=”swift”]let pageData:NSArray = ["I’m as proud of what we don’t do as I am of what we do – Steve Jobs", "That’s one small step for man, one giant leap for mankind – Neil Armstrong","An ant on the move does more than a dozing ox – Lao Tzu","I mean, it’s impossible But that’s exactly what we’ve tried to do – Jonathan Ive"]
[/code]

 

Then delete the following lines from init() function

[code language=”swift”]// Create the data model.

let dateFormatter = NSDateFormatter()

pageData = dateFormatter.monthSymbols[/code]

 

Now compile and run the app on the simulator to see a Simple Page-based app in action written in Swift.

201408131315.jpg

Since we had gone with the default page-based template, we are unaware of the logic behind UIPageViewController. In another post, I will try to build a UIPageViewController from scratch without using the template and see more about the UIPageViewControllerDelegate and UIPageViewControllerDataSource.

Download source code from here

Filed Under: Develop, ios, iPhone, Programming, Xcode Tagged With: PageBaed App, Swift, Xcode

UIGestureRecognizer in Swift

July 23, 2014 By Ravi Shankar 9 Comments

In this short tutorial, we will see the steps required for implementing UIGestureRecognizer in Swift programming language. Let us take the previous Stop Watch demo code and implement tap, double tap and swipe gestures. You can download source code for Stop Watch from here.

201407231513.jpg

The following features will be implemented using the UIGestureRecognizer.

  • Tap – Starts the timer.
  • Double Tap – Stops the timer
  • Swipe (from left to right) – Resets the timer.

Remove the buttons

Since we are replacing the buttons with gestures, these buttons can be removed from the View Controller. Navigate to Main.storyboard and select the Start and Stop buttons and delete them. Make sure the timer label is centre aligned both vertically and horizontally. Then click Reset to Suggested Constraints under Resolve Auto Layout Issues option.

201407231527.jpg

Write Gestures code

Click SWViewController.swift file in the Project navigator and navigate to viewDidLoad function. Then add the following code to viewDidLoad method

  override func viewDidLoad() {

super.viewDidLoad()

  

let aSelector : Selector = “start:”

let tapGesture = UITapGestureRecognizer(target: self, action: aSelector)

tapGesture.numberOfTapsRequired = 1

view.addGestureRecognizer(tapGesture)

  

}

First this creates a constant to hold the selector argument which will be used when creating UITapGestureRecognizer. We are reusing the function that was used for the Start button.

Then we specify the numberOfTapsRequried and add the gesture as part of the view. Now repeat this for the stop button as well but for double tap.

  let bSelector : Selector = “stop:”

let doubleTapGesture = UITapGestureRecognizer(target: self, action: bSelector)

doubleTapGesture.numberOfTapsRequired = 2

view.addGestureRecognizer(doubleTapGesture)

  

tapGesture.requireGestureRecognizerToFail(doubleTapGesture)

The only difference is the number of taps required is specified as 2 and we are specifying that the single tap function will be called only when gesture is not double tap. Now if you try to run this project in the simulator, you should be able start and stop the timer using tap and double tap gestures.

Adding Swipe Gesture

When the user does a swipe from left to right, the values in the timer label must be set to 00:00:00. We can do this by using the UISwipeGestureRecognizer. Let us first the add function that resets the timer label.

  @IBAction func reset(sender: AnyObject) {

displayTimeLabel.text = “00:00:00”

}

Then add the following code to viewDidLoad method

  let cSelector : Selector = “reset:”

let rightSwipe = UISwipeGestureRecognizer(target: self, action: cSelector)

rightSwipe.direction = UISwipeGestureRecognizerDirection.Right

view.addGestureRecognizer(rightSwipe)

When a swipe from left to right is done the reset function is called. The viewDidLoad function with all the Gesture Recognizer should look as shown below.

  override func viewDidLoad() {

super.viewDidLoad()

  

let aSelector : Selector = “start:”

let tapGesture = UITapGestureRecognizer(target: self, action: aSelector)

tapGesture.numberOfTapsRequired = 1

view.addGestureRecognizer(tapGesture)

  

let bSelector : Selector = “stop:”

let doubleTapGesture = UITapGestureRecognizer(target: self, action: bSelector)

doubleTapGesture.numberOfTapsRequired = 2

view.addGestureRecognizer(doubleTapGesture)

  

tapGesture.requireGestureRecognizerToFail(doubleTapGesture)

  

let cSelector : Selector = “reset:”

let rightSwipe = UISwipeGestureRecognizer(target: self, action: cSelector)

rightSwipe.direction = UISwipeGestureRecognizerDirection.Right

view.addGestureRecognizer(rightSwipe)

}

Try running the project in simulator and check out tap, double tap and swipe gestures.

201407231555.jpg

Source code

Filed Under: Develop, ios, Xcode Tagged With: Swift, UIGestureRecognizer, UISwipeGestureRecognizer, UITapGestureRecognizer, Xcode

Simple StopWatch app in Swift

July 22, 2014 By Ravi Shankar 53 Comments

In this tutorial, we will see the steps for creating simple StopWatch app in Swift Programming language as shown in the below screenshot.

SimpleStopWatch demo

Click File menu -> New -> select Project from menu list.

Single View Application Xcode

Choose the template as Single View Application and click Next button.

Xcode select language as Swift

Enter name of the Product, Language as Swift then click Next to specify a folder and save the project.

Project Navigator in Xcode

Navigate to Project Navigator and select Main.storyboard. Using the Attributes Inspector, change the background colour for the ViewController to Dark Gray Colour

Attributes Inspector for View Controller

Navigate to Object Library, drag and drop UILabel to View Controller. Then align the label horizontally centred to the View Controller. Using the Attributes Inspector enter the label text as 00:00:00, change the colour to White, make the text centre aligned and increase the the font size to 27.0

Attributes Inspector for UILabel

Now drag and drop two buttons for starting and stopping the timer. Change the button text to Start and Stop respectively and set the Text Color to white.

201407221034.jpg

Now select ViewController.swift in the Project Navigator and delete the file, select Move to Trash in the Confirmation box.

201407221037.jpg201407221054.jpg

Let us add a new UIViewController file, right click on the SimpleStopWatch folder and select New File from the menu list.

201407221039.jpg

Select the template for the new file as Cocoa Touch Class (under iOS), then click Next

201407221042.jpg

Enter the name of the class as SWViewController, Subclass as UIViewController and Language as Swift. Then click Next and choose the Project folder to save the file.

201407221044.jpg

Navigate to SWViewController.swift and add a IBOutlet for UILabel.

[code language=”swift”]@IBOutlet var displayTimeLabel: UILabel!
[/code]

Then add two IBActions method for the two buttons, Start and Stop.

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

@IBAction func stop(sender: AnyObject) {
}
[/code]

 

Navigate to Main.storyboard, select View Controller and specify the class name as SWViewController using the Identify Inspector

Identity Inspector for Class name

Now you should be able to see the IBActions and IBOutlet defined in the class file using Connection Inspector

Connections Inspector in Xcode 6

Drag and connect the UILabel with the IBOutlets, similarly connect IBActions with the buttons and specify the event as Touch Up Inside.

201407221100.jpg

Select the ViewController under View Controller Scene, click the Resolve Auto Layout Issues option and select Reset to Suggested Constraints. This would ensure that the alignment of controls remains the same for different screen size.

201407221108.jpg

Now if you try to run this project on Simulator, the screen would be as shown below. Nothing should happen on clicking the two buttons as we are yet to add the functionality.

201407221111.jpg

Write Code logic for StopWatch

Navigate to SWviewController.swift file and new function name as updateTime. This function will be used for calculating the time in minutes, seconds and fraction of milliseconds.

Add a new class level variable to the class for storing the start time.

[code language=”swift”]var startTime = NSTimeInterval()[/code]

Then add the following code in updateTime method. This is used for calculating the StopWatch time and assigning the value to the UILabel.

[code language=”swift”]</pre>
func updateTime() {

var currentTime = NSDate.timeIntervalSinceReferenceDate()

//Find the difference between current time and start time.

var elapsedTime: NSTimeInterval = currentTime – startTime

//calculate the minutes in elapsed time.

let minutes = UInt8(elapsedTime / 60.0)

elapsedTime -= (NSTimeInterval(minutes) * 60)

//calculate the seconds in elapsed time.

let seconds = UInt8(elapsedTime)

elapsedTime -= NSTimeInterval(seconds)

//find out the fraction of milliseconds to be displayed.

let fraction = UInt8(elapsedTime * 100)

//add the leading zero for minutes, seconds and millseconds and store them as string constants

let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)

//concatenate minuets, seconds and milliseconds as assign it to the UILabel

displayTimeLabel.text = “\(strMinutes):\(strSeconds):\(strFraction)”

}[/code]

Add a new class level NSTimer variable as shown below.

[code language=”swift”]</pre>
var timer = NSTimer()[/code]

Navigate to Start IBAction function and add the following the code.

 

[code language=”swift”]@IBAction func start(sender: AnyObject) {
let aSelector : Selector = “updateTime”
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
[/code]

This would start a timer and it repeats at regular time interval of 0.01. Here we specify the “updateTime” function which gets called regularly after the specified interval. We also initialise the startTime variable to the current time. Now when the user taps on Stop button, timer is invalidated and set to nil.

[code language=”swift”]
@IBAction func stop(sender: AnyObject) {
timer.invalidate()
timer == nil
}
[/code]

If you try to run this app on the simulator, you should notice the start and stop functionality works and time is getting displayed in the Label. But the user can repeatedly tap the Start button. So when the clock is running if the user taps the Start button, clock restarts again. We can prevent this by adding the following check to start the timer only when the timer is not running.

[code language=”swift”]@IBAction func start(sender: AnyObject) {
if !timer.valid {
let aSelector : Selector = “updateTime”
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
}[/code]

Download the source code from here

Filed Under: Develop, ios, Programming, Xcode Tagged With: StopWatch, Swift, Xcode

No such module Cocoa

July 1, 2014 By Ravi Shankar 2 Comments

No such module Cocoa error message is displayed when the type of playground file selected is iOS instead of OS X. Make sure to select Playground under OS X if you want to use Cocoa framework and go for UIKit incase of iOS

Choose a template from your new file

Another alternate way is to change the template using the Playground Settings. Use the toggle option to show the Utilities.

Show the Utilities on Playground

Navigate to Playground Settings section, click the Platform drop down and select OS X from the list. This should also resolve the No such module error on Playground.

Playground Settings

Filed Under: Develop, Programming, Xcode Tagged With: error, Playground, Xcode

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