iPhone/iPad altitude app (written in Swift)

When passing holidays in the mountains one often wants to know the altitude. Well… what’s better than writing an altitude app yourself? That’s what I’ve done:

Altitude app for iPhone
Screenshot of altitude app

It took me no more than 2 hours to complete the job and to come up with the above application. The source code is freely available on Github: Altitude.

Swift/iOS: Moving objects with device motion (tilt screen)

One of the cool things of games on smartphones, is that you can control objects using the device motion. But how do you move an object using device tilt (using Swift 2)?

To do so you need to use the CMMotionManager (which is part of Apple’s CoreMotion framework). So don’t forget to include the framework at the top of your code: import CoreMotion.

You must also create one (single) CMMotionManager instance.

let motionManager: CMMotionManager = CMMotionManager()

And start the motion manager in the didMoveToView() function:

motionManager.startAccelerometerUpdates()

Once the motion manager is up and running, we can retrieve motion data from it using the accelerometerData member.

// Get node of object to move
let paddle = childNodeWithName(PaddleCategoryName) as! SKSpriteNode

// Get MotionManager data
if let data = motionManager.accelerometerData {
    
    // Only get use data if it is "tilt enough"
    if (fabs(data.acceleration.x) > 0.2) {
        
        // Apply force to the moving object
        paddle.physicsBody!.applyForce(CGVectorMake(40.0 * CGFloat(data.acceleration.x), 0))
        
    }
}

If you want to actually move the object, you need to make sure that the object has some physical properties:

// Rectangular physics body around the object
paddle.physicsBody = SKPhysicsBody(rectangleOfSize: paddle.frame.size)
 
// Make it dynamic
paddle.physicsBody!.dynamic = true
 
// We don't want the object to fall of the screen
paddle.physicsBody!.affectedByGravity = false
 
// Add some mass to it
paddle.physicsBody!.mass = 0.02

The data.acceleration member is a struct of type CMAcceleration which contains the acceleration along the x-, y- and z-axis.

struct CMAcceleration {
    var x: Double
    var y: Double
    var z: Double
}

The following image (source) explains the orientation of those axes.

CoreMotion CMAcceleration axes

Atelier Vidéo Virton 1 2015: Les maffiantômes de Virton

Naar jaarlijkse gewoonte ben ik weer een maand op taalkamp geweest als monitor. Zie hier het resultaat van een workshop ‘Vidéo’ na 12 dagen Roeland kamp in Virton.

Comme d’habitude j’ai fait un mois de camp de langue. Voila le résultat de 12 jours à Roeland. Un atelier Vidéo réalisé par 11 jeunes à Virton.

Église Saint-Étienne de Waha

L’Église Saint-Étienne de Waha (of Sint-Stefanuskerk) is een kleine kerk uit de 11de eeuw, gelegen in het dorpje Waha, bij Marche-en-Fammene (provincie Luxemburg). In 2003 verwezenlijkte  Jean-Michel Folon de nieuwe glasramen voor de kerk.

Église Saint-Étienne de Waha
Buitenkant van L’Église Saint-Étienne de Waha
Église Saint-Étienne de Waha (1)
Binnenkant van L’Église Saint-Étienne de Waha

 

 

 

Creating a first iPhone app: Liveblog in Swift

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.

Xcode create Swift Single View app

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”.

Xcode storyboard center responsive

 

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”.

Xcode storyboard responsive constraints textview

 

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.

Xcode add referencing outlet

Xcode outlet name

 

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

class ViewController: UIViewController {


    @IBOutlet weak var textView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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


}

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:

let socket = WebSocket(url: NSURL(scheme: "ws", host: "labs.denbeke.be:1234", path: "/")!)
socket.delegate = self
socket.connect()

At this stage we have everything in place to actually handle the incoming WebSocket messages, which are marshalled in the following JSON format:

{
    "Content":"But even cooler, a native iPhone app written in Swift!",
    "Time":1433942629
}

To do this you need to implement the websocketDidReceiveMessage function:

func websocketDidReceiveMessage(ws: WebSocket, text: String) {

    let json: NSDictionary
    do {
        // Parse JSON request
        try json = NSJSONSerialization.JSONObjectWithData(text.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
        
        // Do something with the parsed JSON data
        if (json["Content"] != nil) {
            textView.text = (json["Content"] as! String) + "\n\n" + textView.text
        }
        
    }
    catch {
        print("Could not parse json message")
    }

    
    print("Received text: \(text)")
}

The above snippet will try to parse the JSON request into a Swift dictionary/map. If this goes without any error, the content of the message will be prepended in the TextView we created earlier.

All together your ViewController should look like this:

import UIKit
import Starscream

class ViewController: UIViewController, WebSocketDelegate  {

    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        // padding of TextView: top, left, bottom, right
        textView.textContainerInset = UIEdgeInsetsMake(8,8,4,8);

        // Setup WebSocket
        let socket = WebSocket(url: NSURL(scheme: "ws", host: "denbeke.be:1234", path: "/")!)
        socket.delegate = self
        socket.connect()

    }

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


    // Interface for WebSockets

    func websocketDidConnect(ws: WebSocket) {
        print("websocket is connected")
    }

    func websocketDidDisconnect(ws: WebSocket, error: NSError?) {
        if let e = error {
            print("websocket is disconnected: \(e.localizedDescription)")
        }
    }

    func websocketDidReceiveMessage(ws: WebSocket, text: String) {

        let json: NSDictionary
        do {
            // Parse JSON request
            try json = NSJSONSerialization.JSONObjectWithData(text.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

            // Do something with the parsed JSON data
            if (json["Content"] != nil) {
                textView.text = (json["Content"] as! String) + "\n\n" + textView.text
            }

        }
        catch {
            print("Could not parse json message")
        }


        print("Received text: \(text)")
    }

    func websocketDidReceiveData(ws: WebSocket, data: NSData) {
        print("Received data: \(data.length)")
    }



}

The complete iPhone app should look like this:

Liveblog iOS iPhone app screenshot

 

I have uploaded the source code of the app to Github: Liveblog-iOS-App

Simple Liveblog to demonstrate WebSockets in Go

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.

Time to create a websocket handler:

func main() {
    http.Handle("/", websocket.Handler(HandleSocket))

    if err := http.ListenAndServe(":1234", nil); err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}

In the above snippet, HandleSocket is the name of your own defined handler function. In this easy example I created a handler function that will just send all received message on a socket back:

func HandleSocket(ws *websocket.Conn) {

    // Wait for incoming websocket messages
    for {
        var reply string

        if err := websocket.Message.Receive(ws, &reply); err != nil {
            log.Println("Can't receive from socket:", err)
            break
        }

        log.Println("Received back from client: " + reply)

        msg := "Received:  " + reply
        log.Println("Sending to client: " + msg)

        if err := websocket.Message.Send(ws, msg); err != nil {
            log.Println("Can't send to socket:", err)
            break
        }
    }
}

Of course I enhanced this Go code to create an actual liveblog demo.

Javascript

Now we have our websocket, we must actually do something with it in Javascript. The most simple implementation will prepend any new message to an html list with id messages:

var sock = null;
var wsuri = "ws://localhost:1234";

window.onload = function() {

    sock = new WebSocket(wsuri);

    sock.onopen = function() {
        console.log("connected to " + wsuri);
    }

    sock.onclose = function(e) {
        console.log("connection closed (" + e.code + ")");
    }

    sock.onmessage = function(e) {
        $('<li>' + e.data '</li>').hide().prependTo('#messages').fadeIn(1000);
    }
};

We must also be able to send messages from an admin panel:

function send() {
    var msg = document.getElementById('new_message').value;
    document.getElementById('new_message').value = '';
    sock.send(msg);
};

Liveblog

I combined the above little pieces to create a simple liveblog. The blog has an admin page on which someone can add messages, which are then broadcasted to all the other sockets.

 

Simple admin page
Simple admin page

The source code of the demo is available on Github: github.com/DenBeke/Liveblog

Antwerpen vanaf Panorama van KBC Boerentoren

Deze week de kans gekregen om wat foto’s te nemen vanop de hoogste verdieping van de KBC Boerentoren.

Het resultaat: een aantal mooie panorama foto’s van Antwerpen…

Zicht op de kathedraal van Antwerpen en de Schelde. Rechts van de kathedraal zie je het Vleeshuis, en uiterst rechts staat de Sint-Pauluskerk. In de verte zie je de koeltorens van Doel. Foto werd genomen van op het panorama in de KBC Boerentoren.
Zicht op de kathedraal van Antwerpen en de Schelde. Rechts van de kathedraal zie je het Vleeshuis, en uiterst rechts staat de Sint-Pauluskerk.
In de verte zie je de koeltorens van Doel.
Bocht van de schelde, met op de voorgrond de Sint-Pauluskerk, rechts het MAS. In de verte op linkeroever valt nog een glimp op te vangen van Oosterweel. Links vooraan zie je ook het Vleeshuis.
Bocht van de schelde, met op de voorgrond de Sint-Pauluskerk, rechts het MAS.
In de verte op linkeroever valt nog een glimp op te vangen van Oosterweel.
Links vooraan zie je ook het Vleeshuis.
Zicht op de Schelde met centraal in beeld de Sint-Andrieskerk
Zicht op de Schelde met centraal in beeld de Sint-Andrieskerk
Politietoren "Den Oudaan" met rechts ernaast de Sint-Augustinuskerk en verderop het nieuwe justitiepaleis op de achtergrond
Politietoren “Den Oudaan” met rechts ernaast de Sint-Augustinuskerk en verderop het nieuwe justitiepaleis op de achtergrond
Van links naar rechts Sint-Antonius en het Sportpaleis (beide in de verte), Sint-Jacobskerk, Theater Building, Antwerp Tower en uiterst rechts Antwerpen-Centraal
Van links naar rechts Sint-Antonius en het Sportpaleis (beide in de verte), Sint-Jacobskerk, Theater Building, Antwerp Tower en uiterst rechts Antwerpen-Centraal

LaTeX and Fuzzy Logics

Fuzzy logics (especially fuzzy numbers and fuzzy intervals) can be beautifully plotted on a graph, …. aaaand of course, you can also do this using LaTeX and pgfplots!

\begin{tikzpicture}
        \begin{axis}[
            height=3.5cm,
            width=\textwidth/2,
            ytick={0,1},
            xtick={4,6},
            area style,
            xlabel={$$},
            xmin=0,xmax=10,
            axis x line=bottom,
            axis y line=left,
            %ylabel={$$},
            enlarge x limits=false
            ]

            \addplot[fill, red, opacity=0.2] coordinates
                {(2.5,0)(4,1)(6,1)(7.5,0)}
                \closedcycle;
                \addplot [red, mark = none, nodes near coords=\textbf{Fuzzy interval},every node near coord/.style={anchor=90,rotate=0,anchor=south,align=center}] coordinates {( 5, 1.1)};

        \end{axis}
\end{tikzpicture}

 

Fuzzy interval
Fuzzy interval plotted with pgfplots in LaTeX

Setup an SSH tunnel on Mac OS X

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!