ViewController与AppDelegate之间的双向通信,适用于iOS的swift 2

问题描述 投票:1回答:1

我正在开发一个iPhone应用程序,它使用PubNub网络将数据发布到Raspberry Pi并订阅来自它的消息。 Xcode 7,Swift 2.这些消息是使用我调用client的对象发送的,该对象在AppDelegate.swift init()方法中声明。我已经能够从我唯一的ViewController成功引用我的AppDelegate,但是从AppDelegate获取数据回到我的ViewController是我的事情变得棘手的地方。

我知道这种双向控制可能并不理想。我不喜欢两个对象彼此了解的概念。但是,由于这是一个小型DIY家庭项目,暂时我想知道如何让我的AppDelegate直接调用ViewController中的一个函数。我在堆栈溢出时发现的所有建议都已过时或无法正常工作。我可以做些什么来轻松地从AppDelegate将String传递给我的ViewController?

更具体一点:我想从AppDelegate底部的client()方法中调用ViewController的setMessage()方法,为ViewController提供我在客户端函数中收到的字符串。

视图控制器

import UIKit

class ViewController: UIViewController {

    var currentMessage = NSString()
    @IBOutlet weak var receivedMessage: UILabel!
    @IBOutlet weak var messageInput: UITextField!
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    @IBAction func sendButtonPressed(sender: AnyObject) {
        let messageToSend = messageInput.text
        appDelegate.client.publish(messageToSend, toChannel: "my_channel", compressed: false, withCompletion: nil)
    }

    func setMessage(message : String) {
        receivedMessage.text = message
    }
}

AppDelegate中

import UIKit
import PubNub

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate, PNObjectEventListener {

    var client : PubNub
    var config : PNConfiguration

    override init() {
        config = PNConfiguration(publishKey: "pub-c-ecaea738-6b0f-4c8d-80a9-a684e405dbe9",
                                 subscribeKey: "sub-c-b71a16f8-5056-11e5-81b5-02ee2ddab7fe")

        client = PubNub.clientWithConfiguration(config)
        client.subscribeToChannels(["my_channel"], withPresence: false)

        super.init()
        client.addListener(self)
    }

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        return true
    }

    func applicationWillTerminate(application: UIApplication) {
        client.unsubscribeFromAll()
    }

    func client(client: PubNub!, didReceiveMessage message: PNMessageResult!) {
        let messageString = String(message.data.message);
        print(messageString)
    }
}
ios iphone swift uiviewcontroller appdelegate
1个回答
0
投票

从你的AppDelegate你可以使用

let vc=self.window!.rootViewController as! ViewController

vc.setMessage(someText)

但是,我会使用NSNotification并让视图控制器订阅它。

© www.soinside.com 2019 - 2024. All rights reserved.