What is Swift-NIO?
This post is a follow-up of Setup Swift-NIO for iOS, tvOS, In the previous tutorial, I spent little time to try to compile the SwiftNIO project for iOS, tvOS. This was done by purpose to make use of Swift-NIO infrastructure for an custom in-app server on iOS, tvOS. That was not that bad.
Just to recap it, Swift-NIO is one of Apple open-source project which provides a reliable networking implementation. You can quickly make up a web server, socket server and so on effortlessly.
One thing to know is that initially Swift-NIO was written for MAC OS and Linux platforms. Therefore the code was completely tied up POSIX socket, and low level Networking C APIs to make the outgoing requests and listen the incoming traffic. The POSIX socket, and low-level Networking C APIs are basically good, standard and recognized across the world. However the downsides of them are:
- Those are primitive APIs. It is hard to write, difficult to read, and maintain later on.
- Not well-optimized for iOS in term of battery life, multi-path network compatibility
- Hard to sync up with the application life-cycle.
Now available for iOS/tvOS
Apple has spent effort to bring Swift-NIO to iOS/tvOS. It is Swift-NIO transport services. This new extension is official unleashed in mid 2019. Any developers are freely to use it in their own project with free of risks.
What is in Swift-NIO transport services? To be simple, Swift-NIO transport services provides some alternative implementations which use Network.framework instead. The Network.framework was introduced few years ago which is aimed to replace POSIX socket and low level Networking APIs. Hence it makes sure maximum compatible to mobile device.
Import Swift-NIO to projects
Swift-NIO and Swift-NIO Transport service are support Swift Package Manager, Hence it is feasibly to import those packages since XCode 11
Firstly, Navigate to Frameworks, Libraries, and Embedded Content sections of the project, Then add packages dependency
Add Swift-NIO package
Add Swift-NIO Transport Service package
Now, You have done importing Swift-NIO and the Transport Service for your project.
Let’s make up a simple HTTP server.
In Xcode, navigate to swift-nio-transport-services > sources > NIOTSHTTPServer > main
There is a sample code of a simple HTTP server in main.swift. You can quickly use this for the sample.
Open main View Controller class, put the code of HTTP1ServerHandler there.
Then We need to set up a sequence of procedures to start up the server
Let’s test the code. First, compile and run the project from XCode and leave it running.
In order to test the server, We can simply do it in Terminal.
Use this command curl -v 127.0.0.1:8888
After all, You should see this outcome below. Good luck.