     }
     
     func appendStringToTextView(_ string: String) {
-        textView.text = "\(textView.text ?? "")\n\(string)"
-        let range = NSMakeRange(textView.text.characters.count - 1, 1)
-        textView.scrollRangeToVisible(range)
+        DispatchQueue.main.async {
+            self.textView.text = "\(self.textView.text ?? "")\n\(string)"
+            let range = NSMakeRange(self.textView.text.characters.count - 1, 1)
+            self.textView.scrollRangeToVisible(range)
+        }
     }
     
     // MARK: - MQTTSessionDelegates
-
+    
     func mqttDidReceive(message: MQTTMessage, from session: MQTTSession) {
-        appendStringToTextView("data received on topic \(message.topic) message \(message.stringRep ?? "<>")")
+        appendStringToTextView("data received on topic \(message.topic) message \(message.payload.stringRep ?? "<>")")
     }
     
     func mqttDidDisconnect(session: MQTTSession, reson: MQTTSessionDisconnect, error: Error?) {

    }
    
    func establishConnection() {
        let host = "localhost"
        let port: UInt16 = 1883
        let clientID = self.clientID()
        
        mqttSession = MQTTSession(host: host, port: port, clientID: clientID, cleanSession: true, keepAlive: 15, useSSL: false)
        mqttSession.delegate = self
        appendStringToTextView("Trying to connect to \(host) on port \(port) for clientID \(clientID)")

        mqttSession.connect {
            if !$0 {
                self.appendStringToTextView("Error Occurred During connection \($1)")
                return
            }
            self.appendStringToTextView("Connected.")

    // http://stackoverflow.com/questions/26845307/generate-random-alphanumeric-string-in-swift
    func randomStringWithLength(_ len: Int) -> String {
        let letters = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".characters)
        
        var randomString = String()
        for _ in 0..<len {
            let length = UInt32(letters.count)
            let rand = arc4random_uniform(length)
            randomString += String(letters[Int(rand)])
        }
        return String(randomString)
    }
}

// This extension is used for random numbers
public extension ExpressibleByIntegerLiteral {
    public static func arc4random() -> Self {
        var r: Self = 0
        arc4random_buf(&r, MemoryLayout<Self>.size)
        return r
    }
}

