在我看来,PubNub 的 Swift 入门文档不适用于 PubNub 4.0 之前的版本。我无法成功建立回调以注册 PubNub。
我的代码:
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 */
}
}
深入研究 PubNub 源代码,这是似乎有问题的地方:
- (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 */
});
}
我对 Swift 和与 Objective C 的集成还比较陌生。我很好奇 respondsToSelector
是否有问题,因为 Objective C 代码正在引用 Swift 代码。
消息肯定会被传递; PubNub 库中还有另一个较低级别的函数,用于记录所有收到的消息。
如有任何帮助,我们将不胜感激。
最佳答案
4.0 之前的版本已弃用,不再像以前那样工作。
我建议完全迁移到最新的 (4.0) SDK,新的 iOS SDK 消除了很多膨胀并且编译速度更快。开始查看 this tutorial .
总而言之,实例化 PubNub 客户端如下所示:
let config = PNConfiguration(
publishKey: "Your_Pub_Key",
subscribeKey: "Your_Sub_Key")
client = PubNub.clientWithConfiguration(config)
client?.addListener(self)
client?.subscribeToChannels(["Your_Channel"], withPresence: false)
新的 didReceiveMessage 函数如下所示:
func client(client: PubNub!, didReceiveMessage message: PNMessageResult!, withStatus status: PNErrorStatus!) {
//Do Something like
//println(message)
}
关于objective-c - PubNub 4.0在Swift中建立回调接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31254856/