Skip to main content

Starting Server side Swift : Kitura



Kitura is a new package based web framework for Swift 3.0 by IBM. As Swift is a compiled language, your Kitura application compiles to a binary that can either act as its own webserver (by default, on port 8090) or as a FastGCI server for use with Nginx or Apache.
       

Features

  • URL routing (GET, POST, PUT, DELETE)
  • URL parameters
  • Static file serving
  • FastCGI support
  • SSL/TLS support
  • JSON parsing
  • Pluggable middleware


Starting first project

To create executable package, create and switch to a directory. For  example I have created a directory with name ‘Todoapp’ and moved in.

Now in the terminal, 


$ swift package init


will create folder structure for Kitura as shown

Todoapp
├── Package.swift
├── Sources
│   └── main.swift
└── Tests

Tip : In case swift file ~/Sources/Todoapp.swift created then rename to ~/Sources/main.swift.

In the  Package.swift  add  ‘dependencies’.




/***** Package.swift ******/ 
import PackageDescription

let package = Package(
    name: “Todoapp",
    dependencies: [
        .Package(url: "https://github.com/IBM-Swift/Kitura.git", majorVersion: 1),
        ])

Note :
- Mentioned versions will change in future.
- Careful while mentioning versions of packages.


When you build, it will download and compile all the package dependencies in Packages directory.
$ swift build


First time it will start downloading dependencies of specified in the package followed by compilation like below 

Resolved version: 1.3.0
Cloning https://github.com/IBM-Swift/LoggerAPI.git
HEAD is now at 06272da Check logging level before invoking logger implementation (#17)
Resolved version: 1.3.0
Cloning https://github.com/IBM-Swift/BlueSocket.git
HEAD is now at 9daa891 Merge pull request #43 from BDHernand/master
Resolved version: 0.12.15
Cloning https://github.com/IBM-Swift/CCurl.git
HEAD is now at 3cfb752 Add header callback helper function (#9)
Resolved version: 0.2.3
Cloning https://github.com/IBM-Swift/BlueSSLService.git
HEAD is now at 417d4e4 Merge pull request #9 from BDHernand/master
Resolved version: 0.12.9
Cloning https://github.com/IBM-Swift/SwiftyJSON.git
HEAD is now at 9c8a8a0 Merge pull request #28 from BDHernand/master
Resolved version: 15.0.2
Cloning https://github.com/IBM-Swift/Kitura-TemplateEngine.git
HEAD is now at 4fe7829 Support Swift 3.0.1 (#9)
Resolved version: 1.1.0
Compile Swift Module 'Socket' (3 sources)
Compile Swift Module 'LoggerAPI' (1 sources)
Compile Swift Module 'KituraTemplateEngine' (1 sources)
Compile Swift Module 'SwiftyJSON' (2 sources)
Compile Swift Module 'SSLService' (1 sources)
Compile CHTTPParser utils.c
Compile CHTTPParser http_parser.c
Linking CHTTPParser
Compile Swift Module 'KituraNet' (34 sources)
Compile Swift Module 'Kitura' (42 sources)
......



After success, let's start with  Print(“Hello World !”); in main.swift
Build again,  and now you can see debug directory has exec file when it says  :
 Linking ./.build/debug/Todoapp 


When execute, it will print those string.
$ .build/debug/Todoapp
Hello World !

Serving GET request

In your main.swift,
 


/********* main.swift *******/
import Foundation
import Kitura
import LoggerAPI
import SwiftyJSON

// Disable buffering
setbuf(stdout, nil)
  
// setup routes
let router = Router()
router.get("/") { _, response, next in
    response.status(.OK).send(json: JSON([“Title 1" : “Task 1"]))
    next()
}

// Start server
Log.info("Starting server")
Kitura.addHTTPServer(onPort: 8090, with: router)
Kitura.run()


Open Browser and hit http://localhost:8090

Will give you response.

{

 “Title 1” : “Task 1”

}

Additional Tips:

1. If you got error 'The dependency graph could not be satisfied because an update to XXXXX.git Required'
Update out dated packages with command :
$ swift package update

2 . Generate Xcode project from the root will make easy to manage your project structure.
$ swift package generate-xcodeproj


Get complete project in my Github.

Popular posts from this blog

Animating label text update - choosing a better way

Recently I published a countdown app .  At one point of development - I have to show a timer on a UILabel which ticks on each seconds. As usual I started  setting text to a label object - self .timerLabel.text = someString Easy piece of cake right !?   But wait ... it won't take much user attention when timer ticks on every seconds. So I decided to make use of a simple animation while label gets text update. I found there are dozens of ways to animate a label. In this short article, I listed 3 best way you can animate text on a label. ( Spoiler Alert 👀- I decided to go with 3rd option)  1. Fade In - Fade out animation : CATransition class has got transition type `fade`. With timing function of CATransition - I was able to see the below result. let animation: CATransition = CATransition () animation.timingFunction = CAMediaTimingFunction (name: CAMediaTimingFunctionName .easeInEaseOut) animation.type = CATransitionType .fade animation.subtype = C...

Prevent Navigationbar or Tabbar overlapping Subview - solved for Card view

Recently, I started with a Card view added as a subview of UIView in a view-controller. When a view controller created along subviews, it tends to use entire screen bounds and also slips behind Tab bar or Navigation bar. In my current situation, it's second case. Casually new iOS developers will write a patch by additional value for coordinate y and subtracting bar height from its size. A lot of them posted in SO threads too : How to prevent UINavigationBar from covering top of view? View got hidden below UINavigationBar iOS 7 Navigation Bar covers some part of view at Top So, how I got solved ? self.edgesForExtendedLayout = [] This  will avoid all subviews in a view controller get behind any bars. Read full apple  documentation on here. Full Source code below :  //Simple view controller where its view layed-out as a card. class WidgetCardViewController : UIViewController { var containerView = UIView () //MARK:- View Controller Life Cyc...

Printing Staircase Pattern : Swift coding challenge

In this post, we can try interesting pattern printing challenge in Swift. The problem statement goes like this " Print a staircase of given size 'n'. Make sure that its base and height are both equal to n, and the image is drawn only using `#` symbols and spaces. The last line is not preceded by any spaces." Expected Output : # ## ### #### ##### ###### Working solution: func makePatternOf ( _ size : Int ) { var str = "" // 1 for index in ( 0 ..< size ) { let stop = size -index-1; // 2 for _ in 0 ..< stop { str. append ( " " ) ; } // 3 for _ in 0 .. . index { str. append ( "#" ) ; } print ( str ) str = "" } } makePatternOf ( 6 ) Loop to visit every row of stair case. Loop for appe...

Implementing autocompletion OTP field in iOS

Long waiting is over. !!  iOS 12 brings Autofill for OTP text field which is close to Android provided a decade back. Previously in iOS we used to toggle between OTP text screen and message inbox.  Which was hard to remember and time consuming resulting a bad user experience. Personally, I have been asked from the client/customer couple of times to implement autocompletion for OTP field and took me a lot of time to convey that it is not possible in iOS. Why Autofill was not possible previously?  We all know that Apple gives at most care for user privacy. When we see iOS architecture, each individual app is like a separate island. There is no inter-app bridge between apps (exception for Keychain and URLSchemes APIs which gives very limited scope). Thus we cannot read message content from inbox. Where to start Autofilling? First of all, the target SMS need to have the OTP Code with prefix string "Code" or "Passcode"on its message content. Beware of OTP c...

UICollectionViewCell shows with wrong size on First time - Solved

We commonly use Collection view where its cell size calculated run time. The flow layout delegate is responsible to return individual cell sizes. BUT in most of the cases, delegate method `collectionView: layout sizeForItem:` expects cell size too early. Before generating actual cell size. extension YourViewController : UICollectionViewDelegateFlowLayout { func collectionView ( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize (width: externalWidth, height: externalHeight) } } For instance, if a cell size depends on external view and its frame is not yet ready - results with wrong (or outdated) cell size. Typically happens for the first time view controller laid out all views. You can find similar queries in StackOverflow community : Collection view sizeForItemNotWorking UICollectionViewCell content wrong size on first load How to refresh UICollec...