【问题标题】:Bi-Directional communication between ViewController and AppDelegate with swift 2 for iOSViewController 和 AppDelegate 之间的双向通信与 iOS 的 swift 2
【发布时间】:2016-06-06 05:40:35
【问题描述】:

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

我知道这种双向控制可能并不理想。我不喜欢两个对象相互了解的概念。但是,由于这是一个小型 DIY 家庭项目,所以我暂时想知道如何让我的 AppDelegate 直接调用 ViewController 中的函数。我发现的关于堆栈溢出的所有建议都已过时或不起作用。我该怎么做才能轻松地将字符串从 AppDelegate 传递给我的 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】:

    从您的 AppDelegate 中,您可以使用

    let vc=self.window!.rootViewController as! ViewController
    
    vc.setMessage(someText)
    

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

    【讨论】:

      猜你喜欢
      • 2012-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      相关资源
      最近更新 更多