I have my NSURLProtocol MyGreatProtocol
. I add it to the URL Loading system,
NSURLProtocol.registerClass(MyGreatProtocol)
I th
Here's a sample code for reading the httpBody:
Swift 5
extension URLRequest {
func bodySteamAsJSON() -> Any? {
guard let bodyStream = self.httpBodyStream else { return nil }
bodyStream.open()
// Will read 16 chars per iteration. Can use bigger buffer if needed
let bufferSize: Int = 16
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
var dat = Data()
while bodyStream.hasBytesAvailable {
let readDat = bodyStream.read(buffer, maxLength: bufferSize)
dat.append(buffer, count: readDat)
}
buffer.deallocate()
bodyStream.close()
do {
return try JSONSerialization.jsonObject(with: dat, options: JSONSerialization.ReadingOptions.allowFragments)
} catch {
print(error.localizedDescription)
return nil
}
}
}
Then, in URLProtocol:
override func startLoading() {
...
if let jsonBody = self.request.bodySteamAsJSON() {
print("JSON \(jsonBody)")
}
...
}
IIRC, body data objects get transparently converted into streaming-style bodies by the URL loading system before they reach you. If you need to read the data:
There is one caveat: the stream may not be rewindable, so don't pass that request object on to any other code that would need to access the body afterwards. Unfortunately, there is no mechanism for requesting a new body stream, either (see the README file from the CustomHTTPProtocol sample code project on Apple's website for other limitations).