Server Side Swift: basic Client-Server communication example for iOS and Android

Server Side Swift: basic Client-Server communication example for iOS and AndroidSuragchBlockedUnblockFollowFollowingJan 6This is a repost of a Q&A pair I wrote on Stack Overflow.

Learning a new technology is a time consuming process.

It was for Android with Java.

And it was again for iOS with Swift.

I’m now faced with the challenge of needing to provide a server backend for both Android and iOS apps.

However, I would like to avoid the large time investment of learning a new language if possible.

From what I have heard, the server code could be written in either Java or Swift, but Swift seems to be to be a much cleaner language so that is why I have chosen to go this route.

I want to make a proof-of-concept example where a server running Swift is able to communicate with an Android and iOS app.

The apps send a request and receive a response.

The content below is my introduction into Server Side Swift.

A basic example involves three things:A Linux server running SwiftAn Android appAn iOS appThe focus of this answer is on the Swift server.

Linux server running SwiftThese directions are based on unit one of the free Udacity course titled Server-Side Swift.

I recommend taking the whole thing.

There have been updates since then, but it explains things slowly and clearly.


Log in over ssh to your Linux serverIn this example we will use a VPS with a static IP.

If you don’t have one you can get one from quite a few places.

LowEndBox has inexpensive options.

I’m using Ubuntu Linux for this example.

You should receive an ip address for the server along with a root password.

Depending on what your VPS has installed, you may want/need to install the following dependencies.

sudo apt-get install nano (text editor, more intuitive than vim)sudo apt-get install git2.

Install swiftenvThis will help you download Swift server and manage different version environments.

The installation directions are pretty clear.

Choose the Git option.

git clone https://github.


git ~/.

swiftenvIf you don’t have git or curl installed, you will need them first:sudo apt-get install curlsudo apt-get install gitAs the instructions describe, you should add these lines to the end of your ~/.

bash_profile file (or in my case it was ~/.


# swiftenvexport SWIFTENV_ROOT="$HOME/.

swiftenv"export PATH="$SWIFTENV_ROOT/bin:$PATH"eval "$(swiftenv init -)"This will allow you to use swiftenv from the command line whenever.

To apply the settings, reload the the bash file from the command line with.





Install SwiftYou could download Swift directly, but it is a lot easier to use swiftenv.

swiftenv install 4.


2You can replace 4.


2 with whatever Swift version you want.

Check the current version here.

You should be able to start Swift now by runningswiftwhich will hopefully give you something like thisWelcome to Swift version 4.


2 (swift-4.



Type :help for assistance.

1>You can enter Swift code here.

When you are finished playing around type :exit to quit.

If there is an error, there may be some more dependencies that you need to install.

This happened to me several times along the way.

Just Google the error and then install whatever you need to with sudo apt-get install.


Create our Swift service projectThis is where we will put the actual Swift server code that will communicate with our Android and iOS apps.

Make a directory for the project and cd into it.

mkdir MyFirstSwiftServercd MyFirstSwiftServerUse the Swift Package Manager on the command line to set up our new project.

swift package init –type executable5.

Include the Kitura web framework for SwiftThe Kitura framework provides the tools to make client-server communication possible.

Kitura is from IBM.

There are a number of other ones (see a comparison).

Perfect is a popular one, but the only tutorial I watched was hard to follow.

Anyway, I’m choosing Kitura for now because the Udacity series was so easy to understand.

In the MyFirstSwiftServer directory that we just created open the Package.

swift file.

nano Package.

swiftEdit it to include the Kitura dependency and target.

You can find the most recent version here.

// swift-tools-version:4.

0// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescriptionlet package = Package( name: "MyFirstSwiftServer", dependencies: [ // Dependencies declare other packages that this package depends on.


package(url: "https://github.


git", from: "2.


0") ], targets: [ // Targets are the basic building blocks of a package.

A target can define a module or a test suite.

// Targets can depend on other targets in this package, and on products in packages which this package depends on.


target( name: "MyFirstSwiftServer", dependencies: ["Kitura"]), ])This is also where you would include SwiftlyJSON, but at the time of this writing there is a bug that prevents it from working.

We don’t need it for our minimal example, though, anyway.


Write the server codeOpen the main.

swift filenano Sources/MyFirstSwiftServer/main.

swiftThen paste in the following code.

This is only slightly modified from the code used in the Udacity course Lesson 1 part 11.

import Kitura// Create a new routerlet router = Router()// Handle HTTP GET requests to /router.

get("/") { request, response, next in response.

send("Hello, Client!") next()}// Add an HTTP server and connect it to the routerKitura.

addHTTPServer(onPort: 8090, with: router)// Start the Kitura runloop (this call never returns)Kitura.

run()Note that we used port 8090.

We will use that when we connect to the server.


Test the serverIn your projects root folder, build the project withswift buildThen run the compiled executable with.


build/debug/MyFirstSwiftServer You can test it by using a web browser and going tohttp://93.



34:8090 // replace 93.



34 with your vps ip addressYou should seeHello, Client!Great!.The server is working.

Android client1.

LayoutIn Android Studio create the following layout2.

Request the INTERNET permissionAdd the following line to the manifest.

<uses-permission android:name="android.



CodeCopy in the code.

Most of this is adapted from Android AsyncTask HTTP GET request Tutorial.

Don’t forget to replace the ip address with your server.

public class MainActivity extends AppCompatActivity { // replace 93.



34 with your vps server ip address private static final String SERVER = "http://93.



34:8090/"; private TextView tvServerResponse; @Override protected void onCreate(Bundle savedInstanceState) { super.

onCreate(savedInstanceState); setContentView(R.


activity_main); tvServerResponse = findViewById(R.


textView); Button contactServerButton = findViewById(R.


button); contactServerButton.

setOnClickListener(onButtonClickListener); } View.

OnClickListener onButtonClickListener = new View.

OnClickListener() { @Override public void onClick(View v) { HttpGetRequest request = new HttpGetRequest(); request.

execute(); } }; public class HttpGetRequest extends AsyncTask<Void, Void, String> { static final String REQUEST_METHOD = "GET"; static final int READ_TIMEOUT = 15000; static final int CONNECTION_TIMEOUT = 15000; @Override protected String doInBackground(Void.

params){ String result; String inputLine; try { // connect to the server URL myUrl = new URL(SERVER); HttpURLConnection connection =(HttpURLConnection) myUrl.

openConnection(); connection.

setRequestMethod(REQUEST_METHOD); connection.

setReadTimeout(READ_TIMEOUT); connection.

setConnectTimeout(CONNECTION_TIMEOUT); connection.

connect(); // get the string from the input stream InputStreamReader streamReader = new InputStreamReader(connection.

getInputStream()); BufferedReader reader = new BufferedReader(streamReader); StringBuilder stringBuilder = new StringBuilder(); while((inputLine = reader.

readLine()) != null){ stringBuilder.

append(inputLine); } reader.

close(); streamReader.

close(); result = stringBuilder.

toString(); } catch(IOException e) { e.

printStackTrace(); result = null; } return result; } protected void onPostExecute(String result){ super.

onPostExecute(result); if (result == null) return; tvServerResponse.

setText(result); } }}4.

Test the Android appRun the app.

Press the button and hopefully you should seeSuccess!.Client-Server communication on Android.

iOS client1.

LayoutIn Xcode create the following layout2.

Disable App Transport SecurityThis is not ideal for a production app, but it will help us avoid an error since our VPS only supports an unencrypted http connection currently.

Add the following key to your Info.

plist file.

<key>NSAppTransportSecurity</key><dict> <key>NSAllowsArbitraryLoads</key> <true/></dict>3.

CodeSee this Q&A for more info about making an HTTP request in Swift.

import UIKitclass ViewController: UIViewController { // replace 93.



34 with your vps server ip address let server = "http://93.



34:8090" @IBOutlet weak var serverResponseLabel: UILabel!.@IBAction func sendRequestButtonTappled(_ sender: UIButton) { guard let url = URL(string: server) else {return} // background task to make request with URLSession let task = URLSession.


dataTask(with: url) { (data, response, error) in if let error = error { print(error) return } guard let data = data else {return} guard let dataString = String(data: data, encoding: String.


utf8) else {return} // update the UI if all went OK DispatchQueue.


async { self.


text = dataString } } // start the task task.

resume() }}4.

Test the iOS appRun the app.

Press the button and hopefully you should seeSuccess!.Client-Server communication on iOS.

UpdateRather than develop separate apps for Android and iOS, I am now learning Flutter, which uses the Dart language.

(Sigh, yes, another language to learn, but it has similarities to both Java and Swift.

) I’m not there yet but I will probably write the backend with Dart as well.

See here, here, here, and here.


. More details

Leave a Reply