Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/97.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何通过不断更新来自MQTT发布服务器的数据来更新UILabel?_Ios_Swift_Event Handling_Mqtt - Fatal编程技术网

Ios 如何通过不断更新来自MQTT发布服务器的数据来更新UILabel?

Ios 如何通过不断更新来自MQTT发布服务器的数据来更新UILabel?,ios,swift,event-handling,mqtt,Ios,Swift,Event Handling,Mqtt,我有一个带有温度传感器的Raspberry Pi,它有一个python脚本,该脚本使用MQTT不断发布温度,并且我为每1秒设置一次间隔。在我正在制作的iOS应用程序中,我有一个MQTTManager类,它有一个mqttClient,订阅其主题并接收带有温度的字符串。在我的应用程序的主视图中,我希望显示温度并不断更新,速度与python脚本发送的速度相同(或接近相同)。到目前为止,我的想法是使用mqtt客户机消息中的消息字符串更新UILabel的文本。我不确定如何在每次发送发布事件时正确更新标签文

我有一个带有温度传感器的Raspberry Pi,它有一个python脚本,该脚本使用MQTT不断发布温度,并且我为每1秒设置一次间隔。在我正在制作的iOS应用程序中,我有一个MQTTManager类,它有一个mqttClient,订阅其主题并接收带有温度的字符串。在我的应用程序的主视图中,我希望显示温度并不断更新,速度与python脚本发送的速度相同(或接近相同)。到目前为止,我的想法是使用mqtt客户机消息中的消息字符串更新UILabel的文本。我不确定如何在每次发送发布事件时正确更新标签文本。我知道我需要为此消息设置某种类型的事件处理程序,但我不确定如何进行。任何帮助都将不胜感激

更新:与代码,我到目前为止。这是我的mqttManager:

//
//  MQTTManager.swift
//  TemperatureApp
//
//  Created by Radoka on 2/10/18.
//  Copyright © 2018 radoslav.genov.1992. All rights reserved.
//

    import UIKit
    import CocoaMQTT

    class MQTTManager: NSObject, CocoaMQTTDelegate {

    static let singleton = MQTTManager()
    let mqttClient = CocoaMQTT(clientID: "iOS Device Emulator", host: "192.168.0.101", port: 1883)
    var connected = false

    override init() {
        super.init()
        print("MQTT Initilalized")
        mqttClient.username = "user"
        mqttClient.password = "pass"
        mqttClient.keepAlive = 60
        mqttClient.delegate = self
        connect()
    }

    public func connect(){
        if mqttClient.connState != .connected && mqttClient.connState != .connecting {
            mqttClient.connect()
        }
      }

}

extension MQTTManager {
    func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) {
        //nothing
    }

    func mqtt(_ mqtt: CocoaMQTT, didPublishMessage message: CocoaMQTTMessage, id: UInt16) {
        //nothing
    }

    func mqtt(_ mqtt: CocoaMQTT, didPublishAck id: UInt16) {
        //nothing
    }

    func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16) {
        if let string = message.string {
            print(string)
        }
    }

    func mqtt(_ mqtt: CocoaMQTT, didSubscribeTopic topic: String) {
        print("Subscribed to topic: ", topic)
    }

    func mqtt(_ mqtt: CocoaMQTT, didUnsubscribeTopic topic: String) {

    }

    func mqttDidPing(_ mqtt: CocoaMQTT) {
        print("PING")
    }

    func mqttDidReceivePong(_ mqtt: CocoaMQTT) {
        print("PONG")
    }

    func mqttDidDisconnect(_ mqtt: CocoaMQTT, withError err: Error?) {
        print("Disconnected with error: ", err!)
    }

    func mqtt(mqtt: CocoaMQTT, didConnect host: String, port: Int) {
        print("Connected to MQTT server.")
        connected = true
    }

    func subscribeToTopic(topic: String) {
        if mqttClient.connState == .connected {
            print("Subscribe to: ", topic)
            mqttClient.subscribe(topic, qos: CocoaMQTTQOS.qos1)
        } else {
            print("Can't subscribe to \(topic). Not connected.")
        }
    }
}
接下来,这是我的MainTableViewController,其中有mqttManager的共享实例:

//
//  MainTableViewController.swift
//  TemperatureApp
//
//  Created by Radoka on 2/9/18.
//  Copyright © 2018 radoslav.genov.1992. All rights reserved.
//

import UIKit
import CocoaMQTT
import CoreData


class MainTableViewController: UITableViewController {

    // MARK: - Table view data source
    @IBOutlet weak var temperature: UILabel!
    let mqttManager = MQTTManager.singleton 
    var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer


    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    @IBAction func connectionTest(_ sender: UISwitch) {
        if sender.isOn {
            mqttManager.connect()
            print("connected")
            mqttManager.subscribeToTopic(topic: "rpi/gpio")
        } else {
            print("not connected")
        }
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 3
    }

    public func setTemperature(){
        //Update text of temperature label 
    }

}

在“设置温度”方法中,我要更新文本标签。这是处理事情的正确方法吗?

我想你可以通过一个简单的
通知来解决这个问题。
首先,您应该在要更新此类标签的位置添加一个观察者,这样做:

class MainTableViewController: UITableViewController {
   override func viewDidLoad() {
      super.viewDidLoad()

      // observe temperature
      NotificationCenter.default.addObserver(forName: NSNotification.Name.init("post_temperature"), object: nil, queue: OperationQueue.main) { [weak self] (notification) in
        self?.temperature.text = notification.object as? String ?? ""
      }
   }
}
然后,当您收到主题中更新的温度时,您应该拨打:

extension MQTTManager {
   func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16) {
      if let string = message.string {
          // post temperature
          NotificationCenter.default.post(name: NSNotification.Name.init("post_temperature"), object: string)
      }
   }
}

我想你可以通过一个简单的
通知
来解决这个问题。
首先,您应该在要更新此类标签的位置添加一个观察者,这样做:

class MainTableViewController: UITableViewController {
   override func viewDidLoad() {
      super.viewDidLoad()

      // observe temperature
      NotificationCenter.default.addObserver(forName: NSNotification.Name.init("post_temperature"), object: nil, queue: OperationQueue.main) { [weak self] (notification) in
        self?.temperature.text = notification.object as? String ?? ""
      }
   }
}
然后,当您收到主题中更新的温度时,您应该拨打:

extension MQTTManager {
   func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16) {
      if let string = message.string {
          // post temperature
          NotificationCenter.default.post(name: NSNotification.Name.init("post_temperature"), object: string)
      }
   }
}

用你目前掌握的代码更新你的问题。清楚地解释你需要的代码帮助。用你目前掌握的代码更新你的问题。清楚地解释你需要的代码帮助。你好,我用我现在的代码更新了我的问题。据我所知,NotificationCenter帖子应该放在我的mqttManager中,而addObserver应该放在我的控制器中?您好,我用现在的代码更新了我的问题。据我所知,NotificationCenter帖子应该放在我的mqttManager中,而addObserver应该放在我的控制器中?