Skip to content

Commit ac43a8b

Browse files
committed
Add error and close callbacks to Swift Realtime service
This change adds support for custom error and close event handlers in the Swift Realtime implementation. Developers can now register callbacks to be notified when connection errors occur or when the connection closes, enabling better error handling and connection state management in applications.
1 parent 0c4f514 commit ac43a8b

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

templates/swift/Sources/Services/Realtime.swift.twig

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,17 @@ open class Realtime : Service {
2222
private var reconnectAttempts = 0
2323
private var subscriptionsCounter = 0
2424
private var reconnect = true
25+
26+
private var onErrorCallback: ((Swift.Error?, HTTPResponseStatus?) -> Void)?
27+
private var onCloseCallback: (() -> Void)?
28+
29+
public func onError(_ callback: @escaping (Swift.Error?, HTTPResponseStatus?) -> Void) {
30+
self.onErrorCallback = callback
31+
}
32+
33+
public func onClose(_ callback: @escaping () -> Void) {
34+
self.onCloseCallback = callback
35+
}
2536

2637
private func startHeartbeat() {
2738
stopHeartbeat()
@@ -211,6 +222,8 @@ extension Realtime: WebSocketClientDelegate {
211222
public func onClose(channel: Channel, data: Data) async throws {
212223
stopHeartbeat()
213224

225+
onCloseCallback?()
226+
214227
if (!reconnect) {
215228
reconnect = true
216229
return
@@ -230,6 +243,8 @@ extension Realtime: WebSocketClientDelegate {
230243
public func onError(error: Swift.Error?, status: HTTPResponseStatus?) {
231244
stopHeartbeat()
232245
print(error?.localizedDescription ?? "Unknown error")
246+
247+
onErrorCallback?(error, status)
233248
}
234249

235250
func handleResponseError(from json: [String: Any]) throws {

0 commit comments

Comments
 (0)