Search code examples
swiftswift2pubnub

Use of undeclared type 'PNChannel' when trying to create a channel in Pubnub


I'm following along the Pubnub docs to create a channel named after my logged in user. Pubnub's website says to use this code:

PNChannel *channel = [PNChannel channelWithName:user.objectId];

I'm coding this in Swift so I changed this to the following:

var channel:PNChannel = PNChannel.channelWithName(currentUser.objectId)

but I get an error Use of undeclared type 'PNChannel'

I have import PubNub in the top of my view controller. I'm new to Pubnub so any help is greatly appreciated.

Thanks!

FINAL EDIT!! Thanks to Mike I was able to get further and figure out how to subscribe to a channel, publish a message to that channel, and then get that message back so I can eventually use it in my app:

@IBAction func sendButton(sender: UIButton) {

        //create Pubnub channel
        config = PNConfiguration(publishKey: "YOUR KEY HERE", subscribeKey: "YOUR KEY HERE")
        client = PubNub.clientWithConfiguration(config)

        let channelName = user.objectId! as String
        //print(channelName)
        let channelArray: [String] = [channelName]
        client.subscribeToChannels(channelArray, withPresence: false)
        client.addListener(self)
        client.publish(self.messageText.text!, toChannel: channelName, compressed: false, withCompletion: nil)
    }


 func client(client: PubNub!, didReceiveMessage message: PNMessageResult!) {
        print("Received: %", message.data.message)

}

Solution

  • I have had trouble with this as well. I couldnt figure out how to work with channel groups. But finally i got this to work for me by just using this line to subscribe...

    self.client?.subscribeToChannels(channels, withPresence: false)
    

    Where channels is an array of String's. Simply create your channels, which should be of type String, and then append all your channels to an array, such as my channels array, and then use the line I show above.

    Also, there are two very helpful tutorials on the PubNub website that are written in Swift that can show you all the basics.

    I can show you a more in depth example of my approach if you need it let me know.