我正在开发一个iPhone应用程序,它使用PubNub网络将数据发布到一个树莓Pi并订阅来自它的消息。代码7,Swift 2。这些消息使用我调用client的对象发送,该对象在AppDelegate.swift init()方法中声明。我已经能够成功地从我唯一的一个ViewController引用我的AppDelegate,但是从AppDelegate将数据返回ViewController对我来说是件棘手的事情。
我知道这种双向控制可能不太理想。我不喜欢两个物体互相了解的概念。但是,由于这是一个小型的DIY家庭项目,目前我想知道如何让AppDelegate直接调用ViewController中的函数。我在堆栈溢出上找到的所有建议都已过期或不起作用。如何从AppDelegate轻松地将字符串传递给ViewController?
更具体地说:我想从AppDelegate底部的client()方法中调用ViewController的setMessage()方法,为ViewController提供在client函数中接收到的字符串。
视图控制器

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
    }
}

应用委托
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)
    }
}

最佳答案

从AppDelegate中可以使用

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

vc.setMessage(someText)

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

关于ios - 适用于iOS的Swift 2在ViewController和AppDelegate之间进行双向通信,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35593574/

10-12 14:44
查看更多