当我的所有PubNub代码都在ViewController类或AppDelegate类中时,一切都很棒,但现在对于某些代码模块化和清理我想在一个单独的.Swift文件中将我的PubNub功能包装起来并利用那。
以下是自定义类的代码示例。实例化此类的对象只是使用一些基本信息构造,可以以JSON的形式发送消息,并且可以注册将在接收消息时执行的回调(在init期间)
使用此方法有两个问题:
当我打开Debug中的状态时,我无法看到此客户端 在Pubnub中控制台,虽然它可以发布,奇怪的是
我无法接收消息并获得回调以运行
这里的问题完全有可能取决于我的面向对象的编程技巧,或者缺乏它。帮助
import Foundation
import PubNub
import SwiftyJSON
public class PubNubWrap: NSObject, PNObjectEventListener {
/*PubNub Keys*/
private let myPublishKey = "pub-xxx"
private let mySubscrbeKey = "sub-xxx"
/*Object specific properties*/
private var client: PubNub
private var configuration: PNConfiguration
private var pubnubID: String
private var roomID: String
/*Callbacks for received messages*/
var handleHelloMessage: () -> Void
/*Message styles*/
private enum PubnubMessageType : String{
case Hello = "Hello"
}
//Publish a message on pubnub
private func publish(json: NSDictionary) {
//return an error, success, and keep retrying
client.publish(json, toChannel: roomID, compressed: false, withCompletion: { (status) -> Void in
if !status.error {
//do nothing
} else {
//process error and/or retry
}
})
}
//Receive a message on pubnub
public func client(client: PubNub!, didReceiveMessage message: PNMessageResult!) {
// Handle new message stored in message.data.message
if message.data.actualChannel != nil {
// Message has been received on channel group stored in
// message.data.subscribedChannel
}
else {
// Message has been received on channel stored in
// message.data.subscribedChannel
}
let json_recv = JSON(message.data.message)
print(json_recv)
if json_recv["MessageType"].isExists(){
let mType = json_recv["MessageType"].string! as PubnubMessageType.RawValue
switch mType {
case "Hello":
handleHelloMessage()
default :
print("How did we get here")
}
}
}
/*Public Methods*/
public init(pubnubID:String, room:String, setHelloHandler: () -> Void) {
self.pubnubID = pubnubID
self.roomID = room
self.handleHelloMessage = setHelloHandler
configuration = PNConfiguration(publishKey: myPublishKey , subscribeKey: mySubscrbeKey)
configuration.uuid = self.pubnubID
client = PubNub.clientWithConfiguration(configuration)
super.init()
client.subscribeToChannelGroups([self.roomID], withPresence: true)
client.addListener(self)
}
public func sendHello() {
let json = ["MessageType": PubnubMessageType.Hello.rawValue,
"me": pubnubID]
publish(json)
}
}