Skip to content

Commit

Permalink
Fix crash when closing WebSocket
Browse files Browse the repository at this point in the history
  • Loading branch information
atdrendel committed Jul 5, 2020
1 parent 4d64bfe commit 6467064
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions Sources/WebSocket/WebSocket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,16 +114,15 @@ public final class WebSocket: WebSocketProtocol {
}

public func close(_ closeCode: WebSocketCloseCode) {
let webSocket: (URLSession, URLSessionWebSocketTask)? = sync {
guard let (session, task) = state.webSocketSessionAndTask else { return nil }
let webSocketTask: URLSessionWebSocketTask? = sync {
guard let (_, task) = state.webSocketSessionAndTask else { return nil }
state = .closing
return (session, task)
return task
}

guard let (session, task) = webSocket else { return }
guard let task = webSocketTask else { return }
let code = URLSessionWebSocketTask.CloseCode(closeCode) ?? .invalid
task.cancel(with: code, reason: nil)
session.invalidateAndCancel()
}
}

Expand All @@ -146,8 +145,8 @@ private extension WebSocket {
return
}

assert(session == webSocketSession)
assert(task == webSocketTask)
assert(session === webSocketSession)
assert(task === webSocketTask)

self.state = .open(webSocketSession, webSocketTask, delegate)
}
Expand Down Expand Up @@ -198,4 +197,10 @@ private class WebSocketDelegate: NSObject, URLSessionWebSocketDelegate {
reason: Data?) {
self.onClose(session, webSocketTask, closeCode, reason)
}

func urlSession(_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?) {
session.invalidateAndCancel()
}
}

0 comments on commit 6467064

Please sign in to comment.