forked from aws-amplify/aws-appsync-apollo-extensions-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAppSyncWebSocketClient+URLSessionDelegate.swift
62 lines (53 loc) · 2.06 KB
/
AppSyncWebSocketClient+URLSessionDelegate.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
// MARK: - URLSession delegate
extension AppSyncWebSocketClient: URLSessionWebSocketDelegate {
enum AppSyncWebSocketClientError: Swift.Error {
case connectionLost
case connectionCancelled
}
public nonisolated func urlSession(
_ session: URLSession,
webSocketTask: URLSessionWebSocketTask,
didOpenWithProtocol protocol: String?
) {
AppSyncApolloLogger.debug("[AppSyncWebSocketClient] Websocket connected")
subject.send(.connected)
}
public nonisolated func urlSession(
_ session: URLSession,
webSocketTask: URLSessionWebSocketTask,
didCloseWith closeCode: URLSessionWebSocketTask.CloseCode,
reason: Data?
) {
AppSyncApolloLogger.debug("[AppSyncWebSocketClient] Websocket disconnected")
subject.send(.disconnected(closeCode, reason.flatMap { String(data: $0, encoding: .utf8) }))
}
public nonisolated func urlSession(
_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Swift.Error?
) {
guard let error else {
AppSyncApolloLogger.debug("[AppSyncWebSocketClient] URLSession didComplete")
return
}
AppSyncApolloLogger.debug("[AppSyncWebSocketClient] URLSession didCompleteWithError: \(error))")
let nsError = error as NSError
switch (nsError.domain, nsError.code) {
case (NSURLErrorDomain.self, NSURLErrorNetworkConnectionLost), // connection lost
(NSPOSIXErrorDomain.self, Int(ECONNABORTED)): // background to foreground
subject.send(.error(AppSyncWebSocketClientError.connectionLost))
case (NSURLErrorDomain.self, NSURLErrorCancelled):
AppSyncApolloLogger.debug("Skipping NSURLErrorCancelled error")
subject.send(.error(AppSyncWebSocketClientError.connectionCancelled))
default:
subject.send(.error(error))
}
}
}