• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

ios

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

Internationalization and localization of Apps in Xcode 6 and Swift

August 7, 2014 By Ravi Shankar 25 Comments

Internationalisation and Localization of apps is essential when you want the apps to seamlessly support different languages and region. Internationalization refers to process of providing a framework to the app for supporting multiple languages. And Localization refers to the process of making your app to support a particular locale such as German

In this tutorial, we are going to see an example app that supports text, number, date, currency and image localisation for English and German languages. This is done by following the below mentioned steps

  • Use NSNumberFormatter, NSDateFormatter for Number, Currency and Date values.
  • Internationalization of Storyboard.
  • Internationalization of text.
  • Internationalization of images.

English

201408072015.jpg

German

 

201409302136.jpg

Download source code from GitHub

Create a new project by clicking File menu -> New -> Project

201408071400.jpg

Select the template for the Project as Single View Application.

201408071401.jpg

‘

In the next screen, provide a name for the project as “Localisation Demo” and select the Language as “Swift” then specify a location and save the project.

User Interface changes – UILabels and UIImageView on ViewController

 

Navigate to Main.storyboard, click default View Controller. Drag and drop 9 Labels and 1 ImageView from Object Library on to Storyboard. These labels are used for displaying the caption and values as shown in the below screenshot.

201408071642.jpg

Declaring IBOutlets for UIControls

Click ViewController.swift in project navigator and add the following IBOutlets after the class declaration.

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

@IBOutlet var numberLabel: UILabel!

@IBOutlet var currencyLabel: UILabel!

@IBOutlet var dateLabel: UILabel!

@IBOutlet var imageView: UIImageView!
[/code]

Navigate back to Main.storyboard and connect labels and imageView to the respective outlets.

201408071658.jpg

Populate values for the controls.

 

Click ViewController.swift in Project Navigator and create a new function with name as populateValues

[code language=”swift”]func populateValues() {
textLabel.text = “Good Morning”
numberLabel.text = “9999999.999”
currencyLabel.text = “50000”
dateLabel.text = “07/08/2014”
imageView.image = UIImage(named: “hello”)
}[/code]

The above function populates values for all the controls. The values which are assigned for the fields will be displayed in the screen without localization format. Then add this function as part of ViewDidLoad function.

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

Using Add Files to option, add the image hello.png to the Project folder.

201408071755.jpg201408071756.jpg

Now if you compile and run the project on iOS simulator, you should see the follow screen with values for the labels and image view.

201408071759.jpg

We do not see any formatting applied for Number, Date and Currency Values. Now let us see how to use NSNumberFormatter for formatting number and currency field and NSDateFormatter for formatting date field. Add the following properties after populateValues function in ViewController.swift file.

[code language=”swift”]var numberFormatter: NSNumberFormatter {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
return formatter
}
[/code]

[code language=”swift”]
var currencyFormatter: NSNumberFormatter {
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
return formatter
}[/code]

 

[code language=”swift”]var dateFormatter: NSDateFormatter {
let formatter = NSDateFormatter()
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .MediumStyle
return formatter
}
[/code]

 

In the above functions, we are creating respective formatter instances and setting the corresponding styles such DecimalStyle, CurrencyStyle then MediumStyle for date and time values. Now we need to update populateValues function to use these properties for displaying the values.

[code language=”swift”]func populateValues() {
textLabel.text = “Good Morning”
numberLabel.text = numberFormatter.stringFromNumber(9999999.999)
currencyLabel.text = currencyFormatter.stringFromNumber(5000)
dateLabel.text = dateFormatter.stringFromDate(NSDate())
imageView.image = UIImage(named: “hello”)
}

[/code]

Now after applying the correct format, iOS Simulator will use the default system region to display the values for number, currency and date fields

201408071834.jpg

Adding support for another language to your Xcode Project

In order to enable support for German language, first we need to add that language to the Project. This can be done by using the option available as part of Project target. Select the Project folder then the Project target.

201408071715.jpg

Navigate to the Localization section and click the + sign then select German (de) from the list.

201408071718.jpg

Choose the default files listed in the below screen and click Finish.

201408071720.jpg

Now you should see support German language under Localizations section.

201408071720.jpg

Add Localization for controls in Storyboard

First let us see how to add support for another language for the Caption controls in Main.storyboard.

201408071728.jpg

Expand Main.storyboard and click Main.strings (German) . Now enter the German equivalent for Date, Currency, Number and Image as Datum, Währung, Anzahl and Bild. And for rest of the controls, localization will be done in the code.

201408071735.jpg[code language=”plain”]

/* Class = “IBUILabel”; text = “Date :”; ObjectID = “0sh-CK-26C”; */
“0sh-CK-26C.text” = “Datum :”;

/* Class = “IBUILabel”; text = “Number :”; ObjectID = “AeO-ot-XWj”; */
“AeO-ot-XWj.text” = “Anzahl :”;

/* Class = “IBUILabel”; text = “number”; ObjectID = “XDV-eF-gQk”; */
“XDV-eF-gQk.text” = “number”;

/* Class = “IBUILabel”; text = “Image :”; ObjectID = “bvG-x6-Tpx”; */
“bvG-x6-Tpx.text” = “Bild :”;

/* Class = “IBUILabel”; text = “Currency :”; ObjectID = “tVi-KF-Xgb”; */
“tVi-KF-Xgb.text” = “Währung :”;[/code]

Testing Localization changes in iOS Simulator

The changes to Main.storyboard (German) and NSNumberFormatter and NSDateFormatter will have no effect until we set the language and region to German in Xcode debug environment. Click Set the active scheme option and select Edit Scheme from the list.

201408071850.jpg

Navigate to Options under Debug Environment and select German and Germany for Application Language and Application Region.

201408071852.jpg

Now running the app on the iOS simulator should display the captions in german language and apply formats for number, date and currency fields based on German region.

201408071855.jpg

Internationalization of Text using NSLocalizedString

“Good Morning” has to be displayed in the corresponding German language i.e “Guten Morgen”. Add a new File to the project of type Strings and provide a name as Localizable.strings.

201408071912.jpg201408071913.jpg

Select Localizable.Strings in Project Navigator and click Localize button available under File Inspector.

201408071915.jpg

Then Select English in the Localize drop down and make sure to mark German in the Localization section under File Inspector.

201408071917.jpg201408071918.jpg

Now you should be able to expand Localizable.Strings under Project Navigator and see separate files for English and German.

201408071921.jpg

Add the following line in Localizable.Strings (English)

GOOD_MORNING=“Good Morning”;

Add the following line in Localizable.Strings (German)

GOOD_MORNING=“Guten Morgen”;

Now add the corresponding code to use the values from Localizable.Strings file. Click ViewController.swift and change

textLabel.text = “Good Morning”

to

textLabel.text = NSLocalizedString(“GOOD_MORNING”,comment:“Good Morning”)

NSLocalizedString will lookup for the corresponding entry in Localizable.Strings file for the supplied key. Running the app on iOS simulator should not display the German equivalent for “Good Morning”

201409302137.jpg

Internationalization of Images

In the above screenshot, you could see that text in the image is still in English. So we need to add the corresponding image that contains German text and make changes to pick up the entry based on the Application Language. After selecting hello.png in Project navigator, click Localize button under File Inspector. This should provide you with the option to Localize the file in English and German.

201408071954.jpg

Make sure to tick both English and German under Localization section in File Inspector.

201408071955.jpg

Open the Project folder in Finder tool and this should contain two folder for the languages de and en.

201408072004.jpg

Now copy hello.png with german text to de.lproj folder. Do a clean build and run the app on iOS simulator with language and region set to German.

201409302137.jpg

Download source code from GitHub

Filed Under: ios, iPad, iPhone, Programming, Xcode Tagged With: Internationalization, iPad, Localization, Swift, Xcode, Xcode 6

BlogReader App in Swift

July 31, 2014 By Ravi Shankar 28 Comments

In this iOS development tutorial, we will see how to write a blog feed Reader app in Swift Programming Language. For this demo, let us take the blog feed (https://rshankar.com/feed) from Learning Swift and iOS Development blog. This is a WordPress blog and the number of posts in the feed is set to 10 (This is configurable using WordPress Settings). For parsing this feed we will be using NSXMLParser and the parsed data will be displayed in a TableView. Then when the users taps on any post, the post URL will be displayed in a UIWebView.

Download source code from GitHub

201407311416.jpg 201407311417.jpg

Click File menu, select New then Project from the sub menu.

201407311021.jpg

In the template screen, choose Single View Application and click Next.

201407311022.jpg

In the options screen, enter the Product name and select language as Swift. Then choose a folder and save this new Project.

201407311024.jpg

Add a new TableViewController

Navigate to Main.storyboard and delete the default ViewController. From the object library, drag and drop a TableViewController on to the Storyboard.

201407311034.jpg

Now embed this TableViewController in a NavigationController, by clicking Editor menu and selecting Navigation Controller under Embed In menu option.

201407311035.jpg

Select ViewController.swift file under Project Navigator and delete the file.

201407311037.jpg

Right click on the Project folder and select New File option.

201407311038.jpg

In the Choose a template screen, select Cocoa Touch under iOS and click Next button.

201407311039.jpg

In the Choose options for new file screen, enter the class name as “BRTableViewController”, select Subclass of UITableViewController and Language as Swift.

201407311040.jpg

Using NSXMLParser for parsing the blog feed

Navigate to BRTableViewController.swift class declaration, add NSXMLParserDelegate after UITableViewController.

class BRTableViewController: UITableViewController, NSXMLParserDelegate{

This is required as we need to use some of the functions defined in NSXMLParserDelegate for parsing the feed. Now declare a NSXMLParser variable called parser.

var parser: NSXMLParser = NSXMLParser()

Then update the viewDidLoad method with the following code.

  override func viewDidLoad() {

super.viewDidLoad()

let url:NSURL = NSURL(string: “https://rshankar.com/feed”)

parser = NSXMLParser(contentsOfURL: url)

parser.delegate = self

parser.parse()

}

In the above lines of code, we are defining url for holding the feed. Then reinitialising the parser object with url and also setting the parser delegate to self. The parse( ) method would start parsing the feed. Before we write further code let us understand the structure of the blog feed. If you open the feed address (https://rshankar.com/feed) in your browser, you should notice the following XML structure.
201407311107.jpg
Each item element in the above screenshot provides details about the blog post. And on expanding item element, you should notice the following structure.
201407311110.jpg For this demo, we will be using the title and link elements only. The title will be displayed in the TableView and link will be displayed in UIWebView. In order to hold these title and link, let us create a placeholder class with two properties.
Right click on the Project folder, select New File and choose Swift File under iOS. Click Next and save the file as BlogPost.swift to the Project folder.
201407311132.jpg  
Navigate to BlogPost.swift, declare the class name as BlogPost and add two properties for holding title and link.

class BlogPost {

  

  var postTitle: String = String()

var postLink: String = String()

}

201407311200.jpg  
And to hold all the blog posts let us define variable of type array. Navigate to BRTableViewController.swift and add the following code after the parser variable

  var blogPosts: [BlogPost] = []

Implement the delegate method of NSXMLParser

Add the following three methods to BRTableViewController.swift. You can use Xcode autocomplete feature for adding these methods.

  // MARK: – NSXMLParserDelegate methods

  

func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) {

  

}

  

func parser(parser: NSXMLParser!, foundCharacters string: String!) {

  

}

  

func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) {

  

}

  

As already observed in structure of the blog feed, the blog post is specified under the element named item. So we need to do all initialisation of the variables when the parser starts with this element name. Let us add the following the variables to the class declaration.

  var postTitle: String = String()

var postLink: String = String()

var eName: String = String()

Then initialise these variables didStartElement function when elementName is “item”

  func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) {

eName = elementName

if elementName == “item” {

postTitle = String()

postLink = String()

}

}

Then update foundCharacters function with the following code.

  func parser(parser: NSXMLParser!, foundCharacters string: String!) {

let data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

if (!data.isEmpty) {

if eName == “title” {

postTitle += data

} else if eName == “link” {

postLink += data

}

}

}

In the above lines of code, we are removing the white space and newline character set. Then assign the values to corresponding variables if the content is not empty. Make sure to the append the values as the foundCharacters function will be called number of times for the same element name.
Then finally we add the following lines of code to didEndElement function. An instance of BlogPost is created and set with title and link values. Then this object is added to the blogPosts array.

  func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) {

if elementName == “item” {

let blogPost: BlogPost = BlogPost()

blogPost.postTitle = postTitle

blogPost.postLink = postLink

blogPosts.append(blogPost)

}

}

Displaying the content in TableViewController

Navigate to the Table View Data source section and remove the commented line in numberOfSectionsInTableView and set the return value as 1.

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

return 1

}

The number of rows iN the table view will be equivalent to the total count of objects in blogPosts array. Update numberOfRowsInSection to reflect the array count.

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

return blogPosts.count

}

Now uncomment cellForRowIndexPath function and update the function with the following lines of code.

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

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

  

let blogPost: BlogPost = blogPosts[indexPath.row]

cell.textLabel.text = blogPost.postTitle

return cell

}

In the above lines of code, we have changed the cell identifier to “cell”. Then retrieved the content for the cell using the row index path from the blogPosts array. Then assigned the value of post title to cell’s textLabel.

Now navigate to Main.storyboard, select tableview cell and set the Identifier to Cell using the Attributes inspector.

201407311223.jpg

Then navigate to TableViewController and set the Class as BRTableViewController using the Identity inspector.

201407311224.jpg

Now if you compile and run the project in iOS simulator, you should see the list of blog posts as shown in the below screenshot.

201407311252.jpg

Let us make some cosmetic changes to the look of the table view. Navigate to Main.storyboard and add the title to navigation bar as Blog Reader.

201407311254.jpg

Then add the following function to BRTableViewController.swift for adjusting the row height of the tableview cell.

  override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {

return 50.0

}

Now if you try to run the app on the simulator it should look as shown below.

201407311256.jpg

Displaying the post content in UIWebView

Now when users taps on post title, the user must be taken to another screen displaying the content of the post. For this purpose we to add another ViewController and use UIWebView for displaying the post content. Click Main.storyboard and add ViewController from object library to Storyboard. Now hold control and connect the UITableViewCell from BRTableViewController to the new ViewController, set the segue as “Show”. Then Provide the name of the Storyboard segue as viewpost.

201407311302.jpg

Add a UIWebView control from object library to ViewController. Right click on the Project folder and select New File for adding ViewController class.

201407311307.jpg

Select template as Cocoa Touch class and click Next button. Provide a name to the Class as PostViewController with Subclass of UIViewController. Then click Next and save the file to the Project folder.

201407311308.jpg

Using the Identity inspector the set the class name for the ViewController in the storyboard as PostViewController.

201407311311.jpg

Let us also add a UIActivityIndicatorView that would be displayed till the blog post is getting loaded on the WebView.

201407311313.jpg

Open PostViewController.swift file and add IBOutlets for UIWebView and UIActivityIndicatorView controls.

  @IBOutlet var webView:UIWebView!

@IBOutlet var activityIndicator: UIActivityIndicatorView!

In the class declaration, next to UIViewController add UIWebViewDelegate. This is required as we will be implementing two of the UIWebViewDelegate functions.

class PostViewController: UIViewController, UIWebViewDelegate

Then add the following postLink property, the value for this property will be set when the user taps any post on table view.

  var postLink: String = String()

Now update viewDidLoad function with following lines of code

  override func viewDidLoad() {

super.viewDidLoad()

let url: NSURL = NSURL(string: postLink)

let request: NSURLRequest = NSURLRequest(URL: url)

webView.loadRequest(request)

webView.delegate = self

}

The above lines of code, calls loadRequest of UIWebView by passing a NSURLRequest object. Then sets the delegate for webView to self. Now implement the following UIWebView delegate functions for showing and hiding Activity Indicator View.

  func webViewDidStartLoad(webView: UIWebView!) {

activityIndicator.hidden = false

activityIndicator.startAnimating()

}

  

func webViewDidFinishLoad(webView: UIWebView!) {

activityIndicator.hidden = true

activityIndicator.stopAnimating()

}

Finally use the connection inspector in the Interface builder to connect the IBOutlet variables (webView and activityIndicator) to the respective controls on the ViewController.

201407311318.jpg

Navigate to BRTableViewController.swift and add the prepareForSegue function. Check if the identifier is “viewpost” and then retrieve the post details for the selected row using tableView.indexPathForSelectedRow(). Then assign the post web url to viewController’s postLink property.

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

if segue.identifier == “viewpost” {

let blogPost: BlogPost = blogPosts[tableView.indexPathForSelectedRow().row]

let viewController = segue.destinationViewController as PostViewController

viewController.postLink = blogPost.postLink

}

}

Now if you compile and run the project, you should be able to view the post details on tapping any of the post in the table view.

201407311416.jpg

Download source code from GitHub

Filed Under: ios, Programming Tagged With: Blog Reader, Feed Reader, Swift, Wordpress blog

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

Insertion Sort

July 3, 2014 By Ravi Shankar 2 Comments

Insertion Sort algorithm does the following

  • Keeps the sorted numbers from left to right.
  • Compares the left with right and interchanges the number if left is greater than right.

Here is code snippet of Insertion Sort in Swift.

[code language=”swift”]var inputArr:[Int] = [Int]()

// generate random numbers
for rIndex in 0..&lt;10 {
inputArr.append(((Int(arc4random()) % 100)))
}

func insertionSort(var inputArray :[Int]) -&gt; [Int] {
var jIndex:Int,kIndex:Int

for kIndex in 1.. 0 &amp;&amp; inputArray[jIndex-1] &gt;= temp ) {
inputArray[jIndex] = inputArray[jIndex-1]
–jIndex
}
inputArray[jIndex] = temp
}

return inputArray
}

insertionSort(inputArr)[/code]

Filed Under: ios, Mac, Programming, Xcode Tagged With: algorithm, insertion Sort, Swift, Xcode

Reverse a String in Swift

July 2, 2014 By Ravi Shankar 5 Comments

Here is a simple code snippet written in Swift programming language for reversing a string.

import Cocoa


//Assigning a value to a String variable

var str = "Hello, playground"


//Create empty character Array.

var strArray:Character[] = Character[]()


//Loop through each character in the String

for character in str {

//Insert the character in the Array variable.

strArray.append(character)

}


//Create a empty string

var reversedStr:String = ""


//Read the array from backwards to get the characters

for var index = strArray.count - 1; index >= 0;--index {

//Concatenate character to String.

reversedStr += strArray[index]

}


reversedStr


the shorter version to reverse is (thanks Andreas)


var str = “Hello, playground”

var reverseStr = “”

for character in str {

reverseStr = character + reverseStr

}

Reverse a String in Swift Programming language
This code snippet demonstrates the following.

  • How to assign a value to variable.
  • How to create an Array of Characters and assign empty value.(Character)
  • Iterate over the string using for-in loop.
  • How to add new elements to an Array.
  • How to create empty String variable.
  • Use the standard for loop to traverse through an array.
  • Concatenate Strings and character
  • Using for .. in

Filed Under: ios, Programming, Xcode Tagged With: Reverse String, Swift, 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