无法从swift应用程序连接到PubNub

时间:2015-02-09 06:20:21

标签: swift pubnub

我正在尝试将PubNub合并到我的快速应用程序中。我已经通过CocoaPods安装了它,并且无法使基本的“Hello World”应用程序正常工作。

我有一个符合PNDelegate协议的简单视图控制器:

class MessageViewController: CustomViewController, PNDelegate

在此控制器的ViewDidLoadMethod中,我添加了以下内容:

    var config: PNConfiguration = PNConfiguration(forOrigin: "pubsub.pubnub.com", publishKey: Constants.PubNubPublishKey, subscribeKey: Constants.PubNubSubscribeKey, secretKey: Constants.PubNubSecretKey)
    var pubNub: PubNub = PubNub.clientWithConfiguration(config, andDelegate: self)
    pubNub.connect()


    // Define Channel
    var channel: PNChannel =  PNChannel.channelWithName("TestChannel", shouldObservePresence: true) as PNChannel


    // Subscribe on the channel
    PubNub.subscribeOn([channel])

    // Subscribe on the channel
    PubNub.sendMessage("Hello world", toChannel: channel)

我还在同一个视图控制器中添加了以下协议方法:

func pubnubClient(client: PubNub!, didReceiveMessage message: PNMessage!) {
    println(message.message)
}

当我运行应用程序时,大多数情况下,所有内容都会执行,但是永远不会调用didReceiveMessage函数。有时,应用程序崩溃,并显示以下消息:

// Verify that reachability callback was called for correct client
NSCAssert([(__bridge NSObject *)info isKindOfClass:[PNReachability class]],
          @"Wrong instance has been sent as reachability observer");

根据基本的PubNub tutorial,上述内容应足以使其发挥作用。任何人都可以帮我确定缺少什么?

谢谢!

编辑:相关信息;我目前正在模拟器上运行它。不使用实际设备会有任何问题吗?

1 个答案:

答案 0 :(得分:2)

您不希望使用pubnub的单例版本与pubnub实例混合使用。在上面的代码中,您有时使用实例,有时使用sharedInstance ...引用不一样。试试这个:(注意subscribeOn..instance)

var pnConfiguration: PNConfiguration!
var pubNub: PubNub!
pnConfiguration = PNConfiguration(origin: "pubsub.pubnub.com"
        ,publishKey: "demo"
        ,subscribeKey: "demo"
        ,secretKey: ""
        ,cipherKey: "")

pubNub=PubNub.clientWithConfiguration(pnConfiguration,andDelegate:self)
        PNLogger.loggerEnabled(true)
        pubNub.connect()
pubNub.subscribeOn([chnlGroup])
pubNub.observationCenter.addMessageReceiveObserver(self){ (message: PNMessage!) -> Void in
            println("message go instance: { channel: \(message.channel), group: \(message.channelGroup), \nmsg: \(message.message)}");
        }