Install a callback in Swift for PubNub 4.0 to receive messages
It seems to me that the PubNub documentation for getting started in Swift does not apply to versions earlier than PubNub 4.0. I cannot successfully set the callback for registering with PubNub.
My code:
class Communicator: NSObject, PNObjectEventListener {
var pubNubClient: PubNub
override init(){
let config = PNConfiguration(
publishKey: "my_publish_key",
subscribeKey: "my_subscribe_key"
)
pubNubClient = PubNub.clientWithConfiguration(config);
super.init()
pubNubClient.addListener(self)
pubNubClient.subscribeToChannels(["my_channel"], withPresence: false)
}
func didReceiveMessage(client: PubNub!, message: PNMessageResult!){
/* THIS METHOD NEVER GETS REACHED */
}
}
Digging into the PubNub source a bit, this is the area that seems to be having problems:
- (void)addListener:(id <PNObjectEventListener>)listener {
dispatch_async(self.resourceAccessQueue, ^{
if ([listener respondsToSelector:@selector(client:didReceiveMessage:)]) {
/* this block is never reached!!! */
[self.messageListeners addObject:listener];
}
/* Remaining Lines Stripped Away */
});
}
I'm still relatively new to Swift and integrating with Objective C. I'm curious if there is a problem with respondsToSelector
since Objective C code is referencing Swift code.
Messages are definitely passed; there is another down-level function in the PubNub library that logs all received messages.
Any help would be much appreciated.
source to share
Versions prior to 4.0 are outdated and won't work exactly the way they used to.
I would recommend moving to the newest (4.0) SDK entirely, the new iOS SDK removed a lot of bloat and compiles much faster. To start watching this tutorial .
To summarize, creating a PubNub client instance looks like this:
let config = PNConfiguration(
publishKey: "Your_Pub_Key",
subscribeKey: "Your_Sub_Key")
client = PubNub.clientWithConfiguration(config)
client?.addListener(self)
client?.subscribeToChannels(["Your_Channel"], withPresence: false)
And the new didReceiveMessage function looks like this:
func client(client: PubNub!, didReceiveMessage message: PNMessageResult!, withStatus status: PNErrorStatus!) {
//Do Something like
//println(message)
}
source to share
The documentation on parsing the resulting PNMessageResult is scarce. This is how I handled it:
func client(client: PubNub!, didReceiveMessage message: PNMessageResult!) {
let encodedMessage = message.data.valueForKey("message") as! NSDictionary
let messageType = encodedMessage["meta"]! as! String
let messageString = encodedMessage["data"]!["msg"]! as! String
print("PubNub: [\(messageType)] \(messageString)")
}
source to share