Skip to content

Commit 251e7d2

Browse files
committed
Implementing jsonObject with streams api of NSJSONSerialization.
1 parent 4eac74e commit 251e7d2

File tree

2 files changed

+534
-5
lines changed

2 files changed

+534
-5
lines changed

Foundation/NSJSONSerialization.swift

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,8 +202,24 @@ open class JSONSerialization : NSObject {
202202

203203
/* Create a JSON object from JSON data stream. The stream should be opened and configured. All other behavior of this method is the same as the JSONObjectWithData:options:error: method.
204204
*/
205-
open class func jsonObject(with stream: InputStream, options opt: ReadingOptions = []) throws -> AnyObject {
206-
NSUnimplemented()
205+
open class func jsonObject(with stream: InputStream, options opt: ReadingOptions = []) throws -> Any {
206+
var data = Data()
207+
guard stream.streamStatus == .open || stream.streamStatus == .reading else {
208+
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
209+
"NSDebugDescription" : "Stream is not available for reading."
210+
])
211+
}
212+
repeat {
213+
var buffer = [UInt8](repeating: 0, count: 1024)
214+
var bytesRead: Int = 0
215+
bytesRead = stream.read(&buffer, maxLength: buffer.count)
216+
if bytesRead < 0 {
217+
throw stream.streamError!
218+
} else {
219+
data.append(&buffer, count: bytesRead)
220+
}
221+
} while stream.hasBytesAvailable
222+
return try jsonObject(with: data, options: opt)
207223
}
208224
}
209225

0 commit comments

Comments
 (0)