• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

Assertions supported in XCTest

March 23, 2017 By Ravi Shankar Leave a Comment

Here you can find the list of Assertions supported by XCTest and it is essential to know all these assertion if you are practicing Test Driven Development in IOS. You can get this list from XCTestAssertions.h

  • XCTFail(<#format…#>) – This unconditionally fails the test.
  • XCTAssertNil(<#a1#>, <#format…#>) – Failure message when object is not nil.
  • XCTAssertNotNil(<#a1#>, <#format…#>) – Failure message when object is nil
  • XCTAssertEqual(<#a1#>, <#a2#>, <#format…#>) – Failure message when expressions(a1 & a2) are not equal.
  • XCTAssertNotEqual(<#a1#>, <#a2#>, <#format…#>) – Failure message when expressions(a1 & a2) are equal.
  • XCTAssertEqualObjects(<#a1#>, <#a2#>, <#format…#>) – Failure message when objects(a1 & a2) are not equal.
  • XCTAssertNotEqualObjects(<#a1#>, <#a2#>, <#format…#>) – Failure message when objects(a1 & a2) are not equal.
  • XCTAssertEqualWithAccuracy(<#a1#>, <#a2#>, <#accuracy#>, <#format…#>) – Failure message when a1 is not equal to a2 with + or – accuracy.
  • XCTAssertNotEqualWithAccuracy(<#a1#>, <#a2#>, <#accuracy#>, <#format…#>) – Failure message when a1 is equal to a2 with + or – accuracy.
  • XCTAssertNoThrow(<#expression#>, <#format…#>) – Failure message when expression does throw exception.
  • XCTAssertNoThrowSpecific(<#expression#>, <#specificException#>, <#format…#>) – Failure message when expression throws specific exception.
  • XCTAssertNoThrowSpecificNamed(<#expression#>, <#specificException#>, <#exception_name#>, <#format…#>) – Failure message when expression throws specific class with specific name.
  • XCTAssertThrows(<#expression#>, <#format…#>) – Failure message when expression does not throw exception.
  • XCTAssertThrowsSpecific(<#expression#>, <#specificException#>, <#format…#>) – Failure message when expression does not throw specific exception.
  • XCTAssert(<#expression#>, <#format…#>) – Failure message when expression is false.
  • XCTAssertTrue(<#expression#>, <#format…#>) – Failure message when expression is false.
  • XCTAssertFailure(<#expression#>, <#format…#>) – Failure message when expression is true.

Filed Under: Develop, ios, Swift, Xcode Tagged With: Assertions, Xcode, XCTest

Turn off excessive logging in Xcode 8

September 25, 2016 By Ravi Shankar 2 Comments

Xcode 8 shows lots of logging message in the console window when you run the app. If you have any print statement in your app module then it can easily get lost in these warning messages.

One of the solution to avoid this excessive logging is to add a property under enviromental variable section. Navigate to Product menu and select Scheme from the menu list then Edit Scheme (Product -> Scheme -> Edit Scheme )

In the Scheme screen, select Run option. Navigate to Environment Variables section and add new variable OS_ACTIVITY_MODE with value as disable

This shoud prevent these warning/logging messages in Console window. This property has to be configured for each project in Xcode, what would be nice to have is a single configuration in Xcode for all projects 🙂

 

Filed Under: logging, Xcode 8

How to increase number of worksheets Excel

March 18, 2016 By Ravi Shankar Leave a Comment

Microsoft Excel by default contains 3 worksheets while creating a new Workbook. For creating a new workbook you can specify the number of Worksheet that a Workbook needs to contain. This can be modified using Excel Options. Listed below are steps for increasing number of Worksheets for a new Workbook in Excel 2013, Excel 2010 and Excel 2007

In Excel 2013 and Excel 2010 –> Click on File menu and then Options.

increase sheets in Workbook in Excel 2013

In Excel 2007 –> Click on Excel Options and then Popular menu.

Excel Options in Excel 2007

Increase worksheets for new workbook in Excel 2007

Under When creating new workbooks section there is include this many sheets fields. This can be used for increasing the number worksheets while creating a new workbook. The minimum value is 1 and the maximum is 255. Check out the below video demo to increase worksheets size in Excel 2013

Also See: How to move or copy worksheets in Excel 2013

Filed Under: Excel, Excel 2007, Excel 2010, Excel 2013, Office 2007, Office 2010, Office 2013 Tagged With: Decrease sheets, increase sheets, Workbook, Worksheets Size

UITableView Demo in Swift

March 10, 2016 By Ravi Shankar 2 Comments

In this tutorial, we will see some of the common UITableView operations such as Adding, Updating, Deleting and Moving records using Swift.

Let us start with a TableView placed over a ViewController instead of using UITableViewController. By this way you will learn lot more about the functionality of UITableView. Add a new file and select Cocoa Touch Class as a template for the new file.

In “Choose options for your new file” screen, enter the class name as TableViewDemoController with subclass as UIViewController. Then save the new file under your preferred location.

User Interface

Navigate to Main.stotyboard then drag and drop a ViewController from Object Libray to Storyboard. Select the ViewController and click Show Identity Inspection and enter the class name as “TableViewDemoController”

Drag and drop Table View from object library to the View Controlller and make sure Table View is aligned properly. Now place a Table View Cell from object library on top of the TableView.

Set the identifier for Prototype cell to “CellIdentifier” using Show Identity Inspector.

Now select the tableview in the Document Outline pane and click Connection Inspector under Utilies pane. Connect the dataSource and delegate Outlets to the TableViewDemoController (yellow color circle on top View Controller)

Display Data

In this demo, we will be seeing how to display list of Socia Media icons. Here are the steps to load those icons in TableView.

First create a Struct that would act as a place holder for holding the name and image file name. Right click on the Project, select New File. In template screen, choose Swift file and provide name as SocialMedia and save the file.

Edit SocialMedia.swift and add the following code snippet. Apart name and imageName property, this also has computed property that returms UIImage based upon the image file name.

import UIKit

struct SocialMedia {

    var name:String
    var imageName:String
    var image: UIImage {
        get {
            return UIImage(named: imageName)!
        }
    }

}

Now Drag and drop social icon images from folder to Xcode project (download images from gitHub repoistory). Navigate TableViewDemoController.swift and add the following code snippet.

var data:[SocialMedia] = [SocialMedia]()

//MARK:- Populate data   

    func loadData() -&amp;gt; [SocialMedia] {

        data.append(SocialMedia(name:"Evernote",imageName:"evernote"))
        data.append(SocialMedia(name:"Facebook",imageName:"facebook"))
        data.append(SocialMedia(name:"GitHub",imageName:"github"))
        data.append(SocialMedia(name:"Google",imageName:"google"))
        data.append(SocialMedia(name:"LinkedIn",imageName:"linkedin"))
        data.append(SocialMedia(name:"Paypal",imageName:"paypal"))
        data.append(SocialMedia(name:"Pinterest",imageName:"pinterest"))
        data.append(SocialMedia(name:"Twitter",imageName:"twitter"))
        data.append(SocialMedia(name:"Vimeo",imageName:"vimeo"))
        data.append(SocialMedia(name:"YouTube",imageName:"youtube"))

        return data
    }

We have declared an array called data which will hold all the SocialMedia icon related information. The function loadData is used for adding all the social media images. Now call this function in the viewDidLoad method.

override func viewDidLoad() {
	super.viewDidLoad()
	 // call loaddata
	 loadData()
 }

In order display data, ViewController needs to conform UITableViewDataSource protocol. Add UITableViewDataSource to the class declaration next to UIViewController.

class TableViewDemoController: UIViewController, UITableViewDataSource {

Then implement the following methods in TableViewDemoController class, these required methods when a class conforms to UITableViewDataSource protocol.

extension TableViewDemoController: UITableViewDataSource {

    // MARK:- TabvleView dataSource methods

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&amp;gt; Int {
        return data.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&amp;gt; UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier(IDENTIFIER,
            forIndexPath: indexPath)

        let socialMedia = data[indexPath.row]

        cell.textLabel?.text = socialMedia.name

        cell.imageView?.image = socialMedia.image

        return cell
    }
}

Finally we need to create IBOutlet for tableView and connect with tableView control in Storyboard.

@IBOutlet var tableView: UITableView!

Now you should be able to build and run the project. This should show list all Social Media icons as shown below

Customize UITableView

In order the customize the tableview, the TableViewDemoController class needs to conform to UITableViewDelegate protocol. Let us say you want to increase the height of tableview rows. Then implement the function heightForRowAtIndexPath to return the height for each row.

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -&amp;gt; CGFloat {
	return 60.0
}

Build and run the project should show the difference in height.

Add and Update row

Navigate to Main.storyboard and add a new View Controller to Interface builder. This View Controller will be used for capturing name of the icon when adding a new row.

This View Controller has a text field to accept the name of the Social Media icon, Done button to save the entered informatiom and Cancel button to cancel the operation. Make sure to create Unwind segue for Done and Cancel button by Control drag and drop each button to Exit icon on the View Controller. Also provide the identifer for the Unwind segue as addAction and cancelAction.

Navigate to TableViewDemoController and add Bar Button Item to the left hand side. Set the Identifier of Bar Button Item to Add.

Now Control + Drag from the Add button to DetailViewController and select Segue as Push with identifier as “addAction”. Similarly to allow users to edit the existing row, Control + Drag TableView prototype cell to DetailViewController and set identifier for the Push segue as “editAction”.

Add a new Cocoa Touch Class file to the existing project with Sub class as UIViewController and name of the file as DetailViewController. Set this file as the class name in the Identity Inspector of DetailViewController in Interface builder.

Update the DetailViewController.swift and replace the existing code with the following lines of code.

import UIKit

class DetailViewController: UIViewController {

    var socialMedia: SocialMedia?

    @IBOutlet var textFeild:UITextField?

    override func viewDidLoad() {
        super.viewDidLoad()

        if let name = socialMedia?.name {
            textFeild?.text = name
        }
    }

    // MARK:- PrepareForSegue

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

        let name = textFeild?.text
        if var _ = socialMedia {
            self.socialMedia?.name = name!
        } else {
            socialMedia = SocialMedia(name:name!,imageName:"unknown")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

We have declared two variables socialMedia and index which will be populated when user taps an esitsing row in the TableView. Also you should find a IBOutlet for UITextField, make sure to connect this with TextField in the Interface Builder.

In the viewDidLoad function, if the user is editing an existing row then the textfield is updated with that value. The prepareForSegue method is called when the user taps Done or Cancel button. And based on the action, a new social media icon is added or an existing row is updated.

Navigate back to TableViewDemoController and implement the following function that will be called on cancel or done operation in DetailViewController.

//MARK:- Cancel and Done

    @IBAction func cancel(segue:UIStoryboardSegue) {
        // do nothing
    }

    @IBAction func done(segue:UIStoryboardSegue) {

        let detailViewController = segue.sourceViewController as!
        DetailViewController

        let socialMedia = detailViewController.socialMedia

        if let selectedIndex = index {
            data[selectedIndex] = socialMedia!
        } else {
            data.append(socialMedia!)
        }
        tableView.reloadData()
    }

Delete and Move row

Delete operation can be added by implementing the following function in TableViewDemoController.

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
	  switch editingStyle {
		case .Delete:
		// remove the deleted item from the model
	 	data.removeAtIndex(indexPath.row)
 		// remove the deleted item from the `UITableView`
		self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
	   	default:
		 return
   	}
}

This would allow users to swipe and delete a row in TableView. The function checks whether the editing style is Delete, then the row is removed from the array as well from the TableView display.

In order to allow users to move the rows, the tableView editing property needs to be set to true. Add another Bar Button Item, this time to the right of TableViewDemoController and provide the caption as Edit. Then connect this button with the following IBAction function.

//MARK:- Editing toggle

This button acts as a toggle switch to enable or disable tableview edit operation. Now add the following function required for Move operation.

//MARK:- TableViewCell Move row methods
	func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -&amp;gt; Bool {
     	return true
    }

Function canMoveRowAtIndexPath needs to return true and in moveRowAtIndexPath function, the tableView row data gets removed from the original index and inserted in to the new position.

Now the user can tap and hold the move option then drag and drop it to the desired position. When the tableview editing is set to true, it also provides delete button apart from the move operation.

Download the source code from here.

Social Media icons credit to Sebastiano Guerriero

Filed Under: ios, Swift, Uncategorized

Protocol Oriented Programming in Swift

March 10, 2016 By Ravi Shankar Leave a Comment

Object Oriented Programming is a paradigm used by programmers many decaded to solve computer problems by modeling them in to classes. In Swift 2.0 a new programming pattern has been introduced known as Protocol Oriented Programming. In this article, we will the three major feature as part of Protocol Oriented Programming

  • Modeling with Protocols and Structs
  • Protocol Extension
  • Swift Standard Library Extension

Using Protocols and Structs

Let us see an example by modeling Bicylce, MotorBike and Car with Protocols and Structs. Create Vehicle and MotorVehicle protocol with the following property definition

[code language=”swift”]protocol Vehicle {
var speed: Int {get}
var color: String {get}
var yearOfMake: Int {get}
}

protocol MotorVehicle {
var engineSize: Int {get}
var licensePlate: String {get}
}
[/code]

In Swift we can make any type (Class. Struct, Enums) to conform to a Protocol. Let us go for a value type (Struct) and not class as we are moving away from inheritance. And it is always safe to use value type and avoid memory related issues by using object references (Class).

[code language=”swift”]struct Bicyle: Vehicle {
let speed: Int
let color: String
let yearOfMake: Int
}

struct MotorBike: MotorVehicle, Vehicle {
let speed: Int
let color: String
let engineSize: Int
let licensePlate: String
let yearOfMake: Int
}
struct Car: MotorVehicle, Vehicle {
let speed: Int
let color: String
let engineSize: Int
let licensePlate: String
let numberOfDoors: Int
let yearOfMake: Int
}[/code]

In the above code snippet, we have created three strutcs Bicycle, MotorBike and Car. Bicyle conforms to Vehicle but Car and MotorBike conform to both Vehicle and MotorVehicle. Now start creating Cars, Bicycles and MotorBikes using corresponding structs.

[code language=”swift”]let cycle = Bicyle(speed: 10, color: “Blue”,yearOfMake: 2011)
let bike = MotorBike(speed: 65, color: “Red”, engineSize: 100, licensePlate: “HT-12345”,yearOfMake: 2015)
let bmw = Car(speed: 220, color: “Green”, engineSize: 1200, licensePlate: “FC-20 435”, numberOfDoors: 4,yearOfMake: 2016)
let audi = Car(speed: 220, color: “Cyan”, engineSize: 1200, licensePlate: “FC-41 234”, numberOfDoors: 4,yearOfMake: 2013)
[/code]

Protocol Extension

In Swift 2.0, the real power Protocol comes with its ability to add extension. It is not just adding method definition but now Protocol allows you to add implemenation as well. Let us say you want to compare vehicles based on yearOfMake attribute. All you need to do is to add an extension for Vehicle Protocol

[code language=”swift”]extension Vehicle {
func isNewer(item: Vehicle) -> Bool {
return self.yearOfMake > item.yearOfMake
}
}
// comparing audi and bmw should return false
audi.isNewer(bmw)[/code]

Swift Standard Library Extension

You can also add extension to Swift standard library such CollectionType, Range, Array etc.. Let us take the following scenario where you have an array of MotorBikes and want to filter them based on licensePlate information.

[code language=”swift”]let bike1 = MotorBike(speed: 65, color: “Red”, engineSize: 100, licensePlate: “HT-12345”,yearOfMake: 2015)
let bike2 = MotorBike(speed: 75, color: “Black”, engineSize: 120, licensePlate: “RV-453”,yearOfMake: 2013)
let bike3 = MotorBike(speed: 55, color: “Blue”, engineSize: 80, licensePlate: “XY-5 520”,yearOfMake: 2012)
let bike4 = MotorBike(speed: 55, color: “Red”, engineSize: 80, licensePlate: “XY-7 800”,yearOfMake: 2009)

let motorbikes = [bike1,bike2, bike3, bike4]
[/code]

How about filtering of all Small Mopeds based on licensePlate containing “XY” characters. This can be achieved by adding an extension to CollectionType which conforms to MotorVehicle protocol. Then create a new function “filterLicensePlate” as shown below

[code language=”swift”]extension CollectionType where Generator.Element:MotorVehicle {
func filterLicensePlate(match:String -> [Generator.Element] {
var result:[Generator.Element] = []
for item in self {
if item.licensePlate.containsString(match) {
result.append(item)
}
}
return result
}
} [/code][code language=”swift”]let motorbikes = [bike1,bike2, bike3, bike4]
// fiter only small mopeds based on XY
motorbikes.filterLicensePlate(“XY”).count
[/code]

Hope you found this introduction to Protocol Oriented Programming useful. Please use the comment section to add your feedback/suggestion.

References

WWDC 2015 – Protocol Oriented Programming
Mixing and Traits in Swift 2.0
Protocol-Oriented Programming in Swift 2
Introducing Protocol-Oriented Programming in Swift 2

Filed Under: ios, Swift 2 Tagged With: Protocol, Protocol Oriented Programming, Struct

Content Priority in Auto Layout

March 4, 2016 By Ravi Shankar 1 Comment

Auto Layout brings in lots of good features to ease the life of an iOS developer when designing User Interfaces. In this example, we will see how to use Content Priorities such as Content Hugging and Comrpession Resistance.

I have created a project with Single View Template and dispayed Size Classes as we are going to focus only on iPhone family.

Drag and drop two labels adjacent to each other.

Add Leading Space and Vertical Space constraints for Label A. Similarly add Vertical Space and Trailing Space constraints for Label B

 

Constraints for Label A

Constraints for Label B

Click the Update Frames option under the Resolve AutoLayout Issues menu. This should align the frames to reflect the constraints changes.

Change the background colour of Labels to Yellow and Green respectively. This would help us to identity the growth of each labels. Now add the Horizontal Spacing constraint between these two labels and set constant to 5.

Now Label B has grown and covered the space between both labels. Please note that this would be in random nature some times even Label A can fill up the space between these labels. And in this article, we will see how to control this behaviour. You will also notice the warning message that “2 views are horizontally ambitguous”. This is because Auto Layout does not know which label should grow and shrink in size.

Content Compression Resistance Priority

Let us change the text for Label in left hand side as “Content Hugging”. Simialrly enter the text for right hand side label as “Compression Resistance”. Then Update Frames to refelect the Intrinsic Content Size changes. You will notice that the Compression Resistance has a truncated trail.

If you want to this label to resist shrinking its size then set the Content Compression Resistance Priority (Under Size Inspector) to value higher than the label on left hand side.

After changing the value from 750 to 751, you will notice the warning messages “Frame will be different at run time”. Now Updating the Frames for All Views in Container shoud reflect as shown in the below screenshot.

Content Hugging Priority

Now Content Hugging label is partially hidden and it cannot grow horizontally as right hand side label has a higher compression resistance priority. Let us set the number of lines for this lable to 0 (which means it can grow based on the content size). This should again result in “Content Priority Ambiguity” error. This time we can fix this by telling Auto Layout that the label on left hand side has least resistance for growth. Select the label on left hand side, navigate to Size Inspector and set the Content Hugging Priority to lower than right hand side label i.e from 251 to 250.

Click Update Frames to resolve the warning message “Frame for Content Hugging will be different at run time”. The Content Hugging label in shown in two lines.

If you need any assistance in Auto Layout, check out our new iOS 9 Auto Layout Tutorials 50% Off.

Filed Under: Auto Layout, Xcode Tagged With: Compression Resistance, Content Hugging

SwiftExpress – Web Application Server in Swift

February 29, 2016 By Ravi Shankar Leave a Comment

Swift Express is a simple yet powerful web application written in Apple’s Swift language. This is an initiative started by Crossload Labs using Play Framework and Express.js

Installation

SwiftExpress GitHub provides a well documented steps for installing the server on Mac OS X and Linux. I tried this on Mac OS X and the whole setup was completed in less 10 minutes and was able quickly run the demo API request.

Features

Feature supported by Swift Express (Note :- re-published from SwiftExpress GitHub repository)

  • ? Linux support with and without Dispatch
  • 100% asynchronous (Future-based API)
  • Flexible and extensible
  • Full MVC support
  • Swift 2.1 and 2.2 compatible
  • Simple routing mechanism
  • Request handlers chaining
  • Typesafe Error Handlers
  • Templeates: Stencil and Mustache
  • Built-in JSON support
  • Easy creation of RESTful APIs
  • Built-in static files serving
  • Multiple contents types built-in support

A Quick Demo

Let us see a quick demo of JSON API Service deployed on SwiftExpress and consumed by iOS App written Swift.

Project Creation

Make sure to install the required libraries before creating the project. Launch terminal window and type the following

[code language=”plain”]swift-express init APIDemo
[/code]

The project creation should kick start the following set of dependancies updates.

[code language=”plain”]*** No Cartfile.resolved found, updating dependencies
*** Fetching Express
*** Fetching Stencil
*** Fetching CEVHTP
*** Fetching PathToRegex
*** Fetching Regex
*** Fetching GRMustache.swift
*** Fetching TidyJSON
*** Fetching BrightFutures
*** Fetching PathKit
*** Fetching ExecutionContext
*** Fetching Result
*** Checking out CEVHTP at "0.1.0"
*** Checking out GRMustache.swift at "bf7d6031d7e0dd862519eaba2b36b2e11a0d25a9"
*** Checking out Result at "1.0.3"
*** Checking out ExecutionContext at "0.3.1"
*** Downloading Regex.framework binary at "v0.5.2: Linux support final"
*** Downloading Express.framework binary at "v0.3.1: OS X binary build"
*** Checking out PathKit at "0.6.1"
*** Downloading TidyJSON.framework binary at "v1.1.0: faster parser"
*** Downloading PathToRegex.framework binary at "v0.2.0: linux support"
*** Checking out Stencil at "0.5.3"
*** Checking out BrightFutures at "0.4.0"
*** xcodebuild output can be found in /var/folders/gs/586wmrks50b9xdpq1309qn9m0000gn/T/carthage-xcodebuild.hzo8CL.log
*** Building scheme "MustacheOSX" in Mustache.xcworkspace
*** Building scheme "PathKit" in PathKit.xcworkspace
*** Building scheme "Result-Mac" in Result.xcodeproj
*** Building scheme "ExecutionContext-OSX" in ExecutionContext.xcodeproj
*** Building scheme "BrightFutures-Mac" in BrightFutures.xcworkspace
*** Building scheme "Stencil" in Stencil.xcodeproj
ld: warning: linking against dylib not safe for use in application extensions: /Users/ravishankar/Downloads/Demo/APIDemo/Carthage/Checkouts/BrightFutures/Carthage/Build/Mac/ExecutionContext.framework/ExecutionContext
Task: "init" done.[/code]

Navigate to APIDemo project folder and launch APIDemo.xcodeproj

[code language=”plain”]cd APIDemo
open APIDemo.xcodeproj[/code]

You should see the following project structure with main.swift file.

Create JSON API Call

Now edit the main.swift file and add app.views.register(JsonView())to enable JSON API service. This can be added below the app.views.register(StencilViewEngine())

Let us create a JSON Service that returns details about Marathon Runs for 2016. We should register a new API route /marathon/ and the response returned by service has been hard code as shown below. The app.get can be added above the app.listen(9999) method call.

[code language=”swift”]app.get("/marathons/") { request in
//compose the response as a simple dictionary
let response = [
[
"name": "Tokyo Marathon",
"date": "28/02/2016"
],
[
"name": "Dong-A Seoul International Marathon",
"date": "20/03/2016"
],
[
"name": "Aalborg Brutal Marathon",
"date": "25/03/2016"
],
[
"name": "Bath Beat Marathon",
"date": "02/04/2016"
],
[
"name": "Freiburg Marathon",
"date": "03/04/2016"
],
[
"name": "Canberra Marathon",
"date": "10/04/2016"
],
[
"name": "NN Rotterdam Marathon",
"date": "10/04/2016"
],
[
"name": "Vienna City Marathon",
"date": "10/04/2016"
],
[
"name": "Haspa Marathon Hamburg",
"date": "17/04/2016"
],
[
"name": "Blackpool Marathon",
"date": "24/04/2016"
]
]
//render disctionary as json (remember the one we’ve registered above?)
return Action.render(JsonView.name, context: response)
}[/code]

Compiling and run the project in Xcode should show “Express was successfully launched on port 9999” in the console message. Accessing the following url should display the JSON Response as shown below.

Now consuming this JSON service from iOS App using NSURLSession class as shown below.

[code language=”swift”]func loadData() {
let url = NSURL(string:"http://localhost:9999/marathons")

let request = NSURLRequest(URL: url!)

let session = NSURLSession.sharedSession().dataTaskWithRequest(request)
{ (data, response, error) -&gt; Void in

if let error = error {
print("Error " + (error.localizedDescription))
return
}

if let data = data {
do {
let results = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! NSArray
for item in results {
print(item)
self.details.append(item as! [String : String])
}

dispatch_async(dispatch_get_main_queue(), { () -&gt; Void in
self.tableView.reloadData()
})
} catch (let error as NSError) {
print("JSON error" + error.localizedDescription)
}

} else {
print("No response")
return
}
}
session.resume()
}

[/code]

Since we are running the service using http, make sure to add Allow Arbitrary Loads to “YES” (under App Transport Security Settings) in info.plist file.

Looking forward to the production release of Swift Express !!!

Filed Under: ios, Swift, Swift 2 Tagged With: SwiftExpress, Web Service

Keyboard Shortcuts in Xcode

February 19, 2016 By Ravi Shankar Leave a Comment

Listed below are the various keyboard shortcuts in Xcode 7. Symbols corresponding to Mac keyboard used are command (⌘), shift (⇧), control (⌃), option/alt (⌥)

Build, Run, Test

Build ⌘ + B
Clean ⌘ + ⇧ + K
Run Tests ⌘ + U
Run ⌘ + R

Debug

Step Over F6
Step Into F7
Step Out F8
Toggle BreakPoint ⌘ + \
Enable or disable BreakPoints ⌘ + Y
Continue ⌃ + ⌘ + Y

Navigator

Show/Hide ⌘ + 0

Project Navigator ⌘ + 1
Symbol Navigator ⌘ + 2
Find Navigator ⌘ + 3
Issue Navigator ⌘ + 4
Test Navigator ⌘ + 5
Debug Navigator ⌘ + 6
Breakpoint Navigator ⌘ + 7
Report Navigator ⌘ + 8

Utility Pane

Show/Hide ⌘ + ⌥ + 0

File Inspector ⌘ + ⌥ + 1
Quick Help Inspector ⌘ + ⌥ + 2
Identity Inspector ⌘ + ⌥ + 3
Attributes Inspector ⌘ + ⌥ + 4
Size Inspector ⌘ + ⌥ + 5
Connection Inspector ⌘ + ⌥ + 6

File Template Library ⌃ + ⌘ + ⌥ + 1
Code Snippet Library ⌃ + ⌘ + ⌥ + 2
Object Library ⌃ + ⌘ + ⌥ + 3
Media Library ⌃ + ⌘ + ⌥ + 4

Find and Replace

Find in Project ⌘ + ⇧ + F
Find / Replace in Project ⌥ + ⌘ + ⇧ + F

Find ⌘ + F
Find / Replace ⌥ + ⌘ + F
FInd Next ⌘ + G
Find Previous ⌘ + ⇧ + G

Editor

Quickly open file ⌘ + ⇧ + O
Open definition ⌃ + ⌘ + J
Comment / Uncomment ⌘ + /
Assitant Editor ⌘ + ⌥ + ⏎
Hide Assitant Editor ⌘ + ⏎
Related Items menu ⌃ + 1
Indent Selection to Right ⌘ + ]
Indent Selection to Left ⌘ + [
Re Indent ⌃ + I
Reveals Current file in Navigator ⌘ + ⇧ + J
Move focus to editor ⌘ + J

Interface Builder

Selected View Move Up ↑
Selected View Move Down ↓

Update frame ⌥ + ⌘ + =
Update Constraint ⇧ + ⌘ + =
Open all views ⇧ + ⌃ + Click

Documentation

Documentation Popup ⌥ + Click

Filed Under: Uncategorized

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