Apple announced that Swift would become open source at the WWDC keynote (earlier this week). The perfect moment for me to create my very first iOS app (in the newly released Swift 2 and Xcode 7 beta). So I spent a few hours yesterday and created a real-time live blog app as a front-end for the WebSocket Liveblog back-end I’ve written in Go.

Xcode project

First I downloaded the new Xcode 7 beta, and created a new application. File, New, Project. Select iOS, Single View Application. Fill in the needed information (make sure the select Swift as programming language and not Objective-C) and create the project.

CocoaPods

Since I didn’t really figured out how to import external modules from Github (and didn’t want to lose time on doing so) I used the CocoaPods tool. This handy tool manages the dependencies for you. (Comparable to Composer for PHP)

Installing CocoaPods is very simple using the Terminal:

$ sudo gem install cocoapods

In Terminal navigate to your project folder and execute pod init (This will create the Podfile file in the root directory of your project), and append the following content the Podfile:

use_frameworks!
target 'Liveblog' do
pod 'Starscream', '~> 0.9'
end

Now open the Liveblog.xcworkspace Workspace in Xcode. Since Starscream isn’t yet coded in Swift 2, Xcode 7 will ask the convert the code to Swift 2. After the automatic conversion, there will still be some compile errors to fix. You can fix them with auto-fix in Xcode.

Creating the user interface

Next step is designing our iPhone app. (I’m not a designer, nor an UX expert, so I’ll keep it simple, KISS). All of this happens in the Main.storyboard file.

At the bottom of the right sidebar, there are some switches with pre-made things you can include into your project (including code snippets, or creating new files). We need the third tab of that panel, i.e. the panel with UX elements.

View

Our storyboard will already consist of a View, which we can style. I chose to give the main view a sea green background.

Label

Now it’s time to create a title at the top of the view. Drag a label from the right bottom UX panel to the view. Again you can do some styling at the right panel. (I increased the font size a lot, and opted for a white font)

Now we want to center the label on all screen sizes. Therefor you can add ‘responsive’ constraints to your storyboard elements. At the right bottom corner of the storyboard panel, there are 4 buttons. Click on the second button to add aligning constraints: select the horizontal constraint and click on “Add 1 constraint”.

Text View

The same steps need to be followed to create a Text View on the storyboard. Drag the Text View element from the right bottom panel to the storyboard and resize it so it fills the whole view (except the top bar). Again, we want this UI element to fit all screen sizes, so we must add some constraints so it will always cover the whole screen.

Click on the red dashed lines in the constraints panel to ‘enable’ the constraints, and then click on “Add 4 constraints”.

Now launch the app in the iOS simulator and make sure everything is responsive. If everything looks fine, you can remove the sample text from the TextView (since we will load WebSocket data in it)

Add referencing outlet

If we want to actually do something with the TextView, we need to create a referencing outlet for it in the ViewController.swift file. In the right top navigation click on the editor icon (the two overlapping rings). This will open a second, split view with the code of the ViewController. Now press the ctrl key and drag the TextView into the code at the right side and give the outlet a name.

If completed successfully, your ViewController class will look like this:

Adding the WebSockets in Swift

Now we can finally implement the actual WebSockets for our app. Well, not really implementing, because we will be using Starscream’s WebSocket client (as mentioned above in the section of the CocoaPods)

First thing to do is import Starscream above the ViewController class. Next add WebSocketDelegate in the class declaration line to indicate we are implementing the Starscream WebSocketDelegate interface (so we can delegate the WebSocket to the ViewController).

class ViewController: UIViewController, WebSocketDelegate {
// ...
}

Since we defined that ViewController implements the WebSocketDelegate interface, you need to add the functions of that interface to the ViewController:

// websocketDidConnect is called as soon as the client connects to the server.
func websocketDidConnect(socket: WebSocket) {
println("websocket is connected")
}
// websocketDidDisconnect is called as soon as the client is disconnected from the server.
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
println("websocket is disconnected: \(error!.localizedDescription)")
}
// websocketDidReceiveMessage is called when the client gets a text frame from the connection.
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
println("got some text: \(text)")
}
// websocketDidReceiveData is called when the client gets a binary frame from the connection.
func websocketDidReceiveData(socket: WebSocket, data: NSData) {
println("got some data: \(data.length)")
}

Next create the websocket client with the url and the port of your back-end. Append the following code to the viewDidLoad function:

Yesterday I had some time left and thought it was the perfect moment to write a very simple live blog to learn more about WebSockets (in Go).

Go

WebSockets are actually very easy in Go, they work just like the http handler. The required websocket package is not installed by default, but you can easily install the (by Go maintained) package: go get code.google.com/p/go.net/websocket.

There are some apps available to setup an SSH tunnel on OS X, but you can do it very easily in the terminal.

Just start a SOCKS web proxy using this SSH command:

$ ssh -D 8080 -C -N username@myserver.com -p 22

Once your proxy is running you must tell OS X to use this web proxy. Go to System preferences, Network, Advanced. Open the Proxies tab and select SOCKS-proxy.
Set the server: 127.0.0.1, set the port: 8080. Save and apply the settings, and everything should work!

The MacPorts Project is an open-source community initiative to design an easy-to-use system for compiling, installing, and upgrading either command-line, X11 or Aqua based open-source software on the OS X operating system.

The tool is very handy when it comes to installing command line tools for Mac. In this guide I will use it to install Apache, MariaDB and PHP. You could also install them using Homebrew, or use the packages that come with your Mac, but I prefer MacPorts… So if you don’t have MacPorts installed, follow the installation instruction on their website.

Before installing any ports, make sure you have the latest version of the ports tree:

$ sudo port selfupdate

Apache

If you have web sharing enabled on your Mac, you should disable it before continuing. Web sharing can be found under ‘System preferences’, ‘Sharing’, …

Time to install Apache:

$ sudo port install apache2

Whenever your installation is completed, you can edit Apache’s configuration file: /opt/local/apache2/conf/httpd.conf. Probably you want to set DocumentRoot to your local Sites folder. To do this change /opt/local/apache2/htdocs to your local sites folder e.g. /Users/Mathias/Sites.
Don’t forget to verify your changes after every modification you do to httpd.conf!

$ /opt/local/apache2/bin/apachectl -t

When everything is configured, you can start Apache using MacPorts services:

$ sudo port load apache2

Stopping services can be done using the unload statement.

Apache should be functioning right now, more configuration details can be found everywhere on the internet, I’m not gonna explain the whole config file here…

MariaDB (MySQL)

Again, we use MacPorts:

$ sudo port install mariadb-server

Once MariaDB is installed, we need to create the main databases:

$ sudo -u _mysql /opt/local/lib/mariadb/bin/mysql_install_db

Time to start MariaDB:

$ sudo port load mariadb-server

Next we need to create a password for the root user, don’t forget to do this step! This procedure will interactively ask you some security details:

$ /opt/local/lib/mariadb/bin/mysql_secure_installation

If you work a lot with sockets for MySQL/MariaDB, you can create a symbolic link from the default socket path to MacPort’s path:

$ sudo ln -s /opt/local/var/run/mariadb/mysqld.sock /tmp/mysql.sock

You can also specify the socket path in your PHP config file: see below…

Note: MacPorts MariaDB has skip-networking enabled by default in /opt/local/etc/mariadb/macports-default.cnf. If you want to use 172.0.0.1 for your MySQL connections, you should comment out that line.

If you want to use mysql on the command line, you can link mysql to MariaDB:

in Apache’s config file /opt/local/apache2/conf/httpd.conf, add index.php to the DirectoryIndex:

<IfModule dir_module>
DirectoryIndex index.php index.html
</IfModule>

Make sure that Apache includes the PHP config, check your httpd.conf file for the following lines:

# Include PHP configurations
Include conf/extra/mod_php56.conf

Also verify that the .so shared object for PHP is included:

# Load the PHP module
LoadModule php5_module modules/mod_php56.so

Before we can use MySQL in our PHP code, we must set the default socket path in /opt/local/etc/php56/php.ini. Search for mysql.default_socket, mysqli.default_socket and pdo_mysql.default_socket and assign the MariaDB socket to them: /opt/local/var/run/mariadb/mysqld.sock.

If you regularly use PHP from the command line, you also want to link the php command to the MacPorts PHP version:

$ sudo port select --set php php56

If you want to have colored PHP CLI output, you must enable it by installing php posix.

In a perfect world, every software developer writes tons of unit tests, and uses continuous integration to make sure everything keeps working. Travis, PHPUnit and Composer are there to save you a lot of time!

In this blogpost I will explain how to setup Travis and run PHPUnit to run unit tests in a PHP project with Composer.

Composer

Composer is a super awesome dependency manager for PHP. If you don’t use it yet, you are doing it wrong! For this guide I assume you already have a working composer.json file and you know the basics of Composer.

Before you can actually test something you must of course run composer install to download all the dependencies.

PHPUnit

PHPUnit is the ultimate unit testing framework for PHP. Installation instructions can be found here.

Next thing to do is create the phpunit.xml file. This file will contain your PHPUnit configuration and will make it very easy to run the unit tests from the command line.

In this phpunit.xml file I have set some basic variables which might be different for your project. But note the bootstrap argument. Assign the path to your Composer autoload.php file to the bootstrap variable.

Next you must specify the directory where your PHP test files are located.

Travis

The Travis configuration is just a normal PHP config, but before installing, Travis must run composer install.

Push everything to Github and let Travis run your unit tests.

If you want strict synchronization between your local Composer dependencies and remote installations, you must also commit the composer.lock file to your repo. Most people place it in their .gitignore, but it is actually meant to be committed to Git.

Example

If you need a live example of such a configuration, take a look at my ORM (Github / Travis) package. In this package I specified an other Composer vendor directory (core/lib), so I also changed the bootstrap variable in the PHPUnit configuration. You may also ignore the database section in the .travis.yml file…