     }
     
     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.")

    }
    
    @IBAction func sendButtonPressed(_ sender: AnyObject) {
        
        guard let channel = channelTextField.text, let message = messageTextField.text,
            !channel.isEmpty && !message.isEmpty
            else { return }
        
        let data = message.data(using: .utf8)!
        let messageID = UInt16.arc4random()
        
        mqttSession.publish(data, in: channel, withMsgID: messageID, delivering: .atMostOnce, retain: false) {
            if !$1 {
                self.appendStringToTextView("Error Occurred During Publish \($2)")
                return
            }
            self.appendStringToTextView("Published \(message) on channel \(channel)")
        }
    }
    
    // MARK: - Utilities
    
    func clientID() -> String {
        
        let userDefaults = UserDefaults.standard
        let clientIDPersistenceKey = "clientID"
        let clientID: String
        
        if let savedClientID = userDefaults.object(forKey: clientIDPersistenceKey) as? String {
            clientID = savedClientID
        } else {
