@@ -28,6 +28,8 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
28
28
return session
29
29
} ( )
30
30
31
+ private var previousChunkBuffer = " "
32
+
31
33
init ( urlRequest: URLRequest ) {
32
34
self . urlRequest = urlRequest
33
35
}
@@ -47,14 +49,25 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
47
49
onProcessingError ? ( self , StreamingError . unknownContent)
48
50
return
49
51
}
50
- let jsonObjects = stringContent
52
+ processJSON ( from: stringContent)
53
+ }
54
+
55
+ }
56
+
57
+ extension StreamingSession {
58
+
59
+ private func processJSON( from stringContent: String ) {
60
+ let jsonObjects = " \( previousChunkBuffer) \( stringContent) "
51
61
. components ( separatedBy: " data: " )
52
62
. filter { $0. isEmpty == false }
53
63
. map { $0. trimmingCharacters ( in: . whitespacesAndNewlines) }
64
+
65
+ previousChunkBuffer = " "
66
+
54
67
guard jsonObjects. isEmpty == false , jsonObjects. first != streamingCompletionMarker else {
55
68
return
56
69
}
57
- jsonObjects. forEach { jsonContent in
70
+ jsonObjects. enumerated ( ) . forEach { ( index , jsonContent) in
58
71
guard jsonContent != streamingCompletionMarker else {
59
72
return
60
73
}
@@ -77,9 +90,14 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
77
90
let decoded = try JSONDecoder ( ) . decode ( APIErrorResponse . self, from: jsonData)
78
91
onProcessingError ? ( self , decoded)
79
92
} catch {
80
- onProcessingError ? ( self , apiError)
93
+ if index == jsonObjects. count - 1 {
94
+ previousChunkBuffer = " data: \( jsonContent) " // Chunk ends in a partial JSON
95
+ } else {
96
+ onProcessingError ? ( self , apiError)
97
+ }
81
98
}
82
99
}
83
100
}
84
101
}
102
+
85
103
}
0 commit comments