Skip to content

Commit

Permalink
Merge pull request #249 from davidstump/feature/request-headers
Browse files Browse the repository at this point in the history
Added headers to be sent to Websocket
  • Loading branch information
dsrees authored Sep 29, 2023
2 parents ecb8719 + 60c4277 commit 2ef6942
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
17 changes: 14 additions & 3 deletions Sources/SwiftPhoenixClient/PhoenixTransport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,11 @@ public protocol PhoenixTransport {

/**
Connect to the server

- Parameters:
- headers: Headers to include in the URLRequests when opening the Websocket connection. Can be empty [:]
*/
func connect()
func connect(with headers: [String: Any])

/**
Disconnect from the server.
Expand Down Expand Up @@ -193,13 +196,21 @@ open class URLSessionTransport: NSObject, PhoenixTransport, URLSessionWebSocketD
public var readyState: PhoenixTransportReadyState = .closed
public var delegate: PhoenixTransportDelegate? = nil

open func connect() {
public func connect(with headers: [String : Any]) {
// Set the transport state as connecting
self.readyState = .connecting

// Create the session and websocket task
self.session = URLSession(configuration: self.configuration, delegate: self, delegateQueue: nil)
self.task = self.session?.webSocketTask(with: url)
var request = URLRequest(url: url)

headers.forEach { (key: String, value: Any) in
guard let value = value as? String else { return }
request.addValue(value, forHTTPHeaderField: key)
}

self.task = self.session?.webSocketTask(with: request)


// Start the task
self.task?.resume()
Expand Down
5 changes: 4 additions & 1 deletion Sources/SwiftPhoenixClient/Socket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ public class Socket: PhoenixTransportDelegate {

/// Timeout to use when opening connections
public var timeout: TimeInterval = Defaults.timeoutInterval

/// Custom headers to be added to the socket connection request
public var headers: [String : Any] = [:]

/// Interval between sending a heartbeat
public var heartbeatInterval: TimeInterval = Defaults.heartbeatInterval
Expand Down Expand Up @@ -266,7 +269,7 @@ public class Socket: PhoenixTransportDelegate {
// self.connection?.enabledSSLCipherSuites = enabledSSLCipherSuites
// #endif

self.connection?.connect()
self.connection?.connect(with: self.headers)
}

/// Disconnects the socket
Expand Down

0 comments on commit 2ef6942

Please sign in to comment.