Swift 通知的使用(十一)

这里我写的是个传值的例子,介绍通知,跟OC的使用基本差不多

let center = NSNotificationCenter.defaultCenter()
        center.addObserver(self, selector: "getValue:", name: "name", object: nil)
func getValue(object: NSNotification) ->Void{
        print(object.object)
        print("object")
    }
func click()->Void{
        let dic = NSMutableDictionary()
        dic.setValue("str", forKey: "name")
        print(dic)
        NSNotificationCenter.defaultCenter().postNotificationName("name", object: dic as [NSObject: AnyObject])
        self.dismissViewControllerAnimated(true) { () -> Void in
            //
        }

    }

使用之后记得移除

    deinit{
        // 移除通知
//        NSNotificationCenter.defaultCenter().removeObserver(self, name: "name", object: nil)
//        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

Swift / OC 进阶群: 498143780

SwiftUI 中使用 CocoaMQTT 连接 MQTT 服务器,你需要做以下几个步骤: 1. **添加依赖**:首先,在你的 Xcode 项目中,通过 CocoaPods、Carthage 或手动引入 CocoaMQTT 库。 - 使用 CocoaPods: 在 `Podfile` 中添加 `pod 'CocoaMQTT', '~> <version>'`,然后运行 `pod install`。 - 使用 Carthage: 添加到 Cartfile: `github "CocoaLumberjack/CocoaLumberjack"`, 然后运行 `carthage bootstrap`. 2. **初始化连接**:在 SwiftUI 的 View 或 ViewModel 中,创建一个 `MQTTSession` 对象,并配置它。设置主机名、端口、认证信息等。 ```swift import CocoaMQTT class MQTTViewModel: ObservableObject { @Published var mqttSession: MQTTSession? init() { mqttSession = try? MQTTSession( host: "your_mqtt_server", port: 1883, username: "your_username", password: "your_password" ) mqttSession?.delegate = self // 设置代理为你自己实现的 MQTTDelegate } } ``` 3. **实现 MQTTDelegate**:为了接收 MQTT 通知,你需要实现 `MQTTSessionDelegate` 协议中的方法,如 `connectionDidConnect(_:)`、`connectionLost(_:)` 等。 4. **订阅主题并监听消息**:使用 `subscribe(to:with_qos:completionHandler:)` 方法订阅感兴趣的 MQTT 主题,当收到消息时,会在相应的回调里处理。 5. **处理连接状态和消息**:在适当的地方更新界面以显示连接状态和接收到的消息。 ```swift func connectionDidConnect(_ session: MQTTSession) { print("Connected to MQTT server") } func connectionDidDisconnect(_ session: MQTTSession, error: Error?) { if let error = error { print("Disconnected from MQTT with error: \(error.localizedDescription)") } else { print("Disconnected gracefully.") } } func messageArrived(_ session: MQTTSession, topic: String?, payload: Data) { print("Received message on topic '\(topic ?? "")': \(String(data: payload, encoding: .utf8) ?? "Payload not available")") } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值