@@ -28,6 +28,8 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
28
28
return session
29
29
} ( )
30
30
31
+ private var prevChunkBuffer = " "
32
+
31
33
init ( urlRequest: URLRequest ) {
32
34
self . urlRequest = urlRequest
33
35
}
@@ -47,14 +49,16 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
47
49
onProcessingError ? ( self , StreamingError . unknownContent)
48
50
return
49
51
}
50
- let jsonObjects = stringContent
52
+ let jsonObjects = " \( prevChunkBuffer ) \( stringContent) "
51
53
. components ( separatedBy: " data: " )
52
54
. filter { $0. isEmpty == false }
53
55
. map { $0. trimmingCharacters ( in: . whitespacesAndNewlines) }
56
+ prevChunkBuffer = " "
57
+
54
58
guard jsonObjects. isEmpty == false , jsonObjects. first != streamingCompletionMarker else {
55
59
return
56
60
}
57
- jsonObjects. forEach { jsonContent in
61
+ jsonObjects. enumerated ( ) . forEach { ( index , jsonContent) in
58
62
guard jsonContent != streamingCompletionMarker else {
59
63
return
60
64
}
@@ -77,7 +81,12 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
77
81
let decoded = try JSONDecoder ( ) . decode ( APIErrorResponse . self, from: jsonData)
78
82
onProcessingError ? ( self , decoded)
79
83
} catch {
80
- onProcessingError ? ( self , apiError)
84
+ if index == jsonObjects. count - 1 {
85
+ // Chunk ends in a partial JSON
86
+ prevChunkBuffer = " data: \( jsonContent) "
87
+ } else {
88
+ onProcessingError ? ( self , apiError)
89
+ }
81
90
}
82
91
}
83
92
}
0 commit comments