问题
I am developing an iPhone app that uses the PubNub network to publish data to a Raspberry Pi and subscribe to messages from it. Xcode 7, Swift 2. These messages are sent using an object that I call client, which is declared in the AppDelegate.swift init() method. I have been able to successfully reference my AppDelegate from my one and only ViewController, however getting data back to my ViewController from the AppDelegate is where things have gotten tricky for me.
I'm aware that this bi-directional control is probably not ideal. I don't like the concept of both objects knowing about each other. However, since this is for a small DIY home project, for the time being I would like to know how I can get my AppDelegate to directly call a function within the ViewController. All of the suggestions I have found on stack overflow are out of date or do not work. What can I do to easily pass a String to my ViewController from the AppDelegate?
To be more specific: I want to call the setMessage() method of my ViewController from within my client() method at the bottom of AppDelegate, giving the ViewController the string that I receive in the client function.
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)
}
}
回答1:
From your AppDelegate you can use
let vc=self.window!.rootViewController as! ViewController
vc.setMessage(someText)
but, I would use an NSNotification
and have the view controller subscribe to that.
来源:https://stackoverflow.com/questions/35593574/bi-directional-communication-between-viewcontroller-and-appdelegate-with-swift-2