Search code examples
swiftpubnub

Cannot connect to PubNub from swift application


I am trying to incorporate PubNub into my swift application. I have installed it through CocoaPods and am failing to get the basic "Hello World" application to work.

I have a simple view controller that conforms to the PNDelegate Protocol:

class MessageViewController: CustomViewController, PNDelegate

In the ViewDidLoadMethod of this controller, I have added the following:

    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)

I have also added the following protocol method to the same view controller:

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

When I run the application, most of the time, everything execute yet the didReceiveMessage function is never called. Sometimes, the application crashes, with the following message:

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

According to the basic PubNub tutorial, the above should be sufficient to get this working. Can anyone help me determine what is missing?

Thanks!

Edit: Relevant info; I am currently running this on a a simulator. Would there be any problem with not using an actual device?


Solution

  • You don't want to mix using the singleton version of PubNub with an instance of pubnub. In your code above you are sometimes using the instance and sometimes using the sharedInstance...the reference is not the same. Try this: (notice 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)}");
            }