我的后端服务器正在使用令牌身份验证,所以我试图订阅一个私有频道,并且按照本教程所说的那样通过实现“ AuthRequestBuilderProtocol”来实现,但是该函数(requestFor)的断点从未被击中,无法订阅该频道。 这是我正在遵循的指南: https://github.com/pusher/pusher-websocket-swift#configuration
这是我到目前为止的代码
var pusher: Pusher!
func initPusher() {
if UserDefaultsAccess.sharedInstance.token != "" {
let opt = PusherClientOptions(authMethod: AuthMethod.authRequestBuilder(authRequestBuilder: AuthRequestBuilder()))
pusher = Pusher(key: "************", options: opt)
pusher.connection.delegate = self
pusher.delegate = self
let channel = pusher.subscribe ("private-user.\(UserDefaultsAccess.sharedInstance.getCurrentAccount().userId)")
let eventName = "App\\Enemts\\MessageSent"
_ = channel.bind(eventName: eventName, callback: { (data: Any?) -> Void in
if let data = data as? [String: AnyObject] {
let text = data["message"] as! String
let author = data["name"] as! String
print(author + ": " + text)
}
})
pusher.connect()
}
}
这是该协议的实现:
class AuthRequestBuilder: AuthRequestBuilderProtocol {
func requestFor(socketID: String, channelName: String) -> URLRequest? {
var request = URLRequest(url: URL(string: "****************/auth")!)
request.httpMethod = "POST"
request.httpBody = "socket_id=\(socketID)&channel_name=\(channelName)".data(using: String.Encoding.utf8)
request.addValue(UserDefaultsAccess.sharedInstance.token, forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Accept")
return request
}
}