Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/enhance capture bodydata #200

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions netfox/Core/NFXProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,43 @@ open class NFXProtocol: URLProtocol

let mutableRequest = (request as NSURLRequest).mutableCopy() as! NSMutableURLRequest
URLProtocol.setProperty(true, forKey: NFXProtocol.nfxInternalKey, in: mutableRequest)

if let bodyData = captureRequestBody(mutableRequest as URLRequest) {
mutableRequest.httpBody = bodyData
}

session.dataTask(with: mutableRequest as URLRequest).resume()
}

func captureRequestBody(_ request: URLRequest) -> Data? {
guard let _ = request.httpBody else {
return nil
}

guard let bodyStream = request.httpBodyStream else {
return nil
}

bodyStream.schedule(in: RunLoop.current, forMode: .default)

let data = NSMutableData()
var buffer = [UInt8](repeating: 0, count: 1024)
bodyStream.open()
while bodyStream.hasBytesAvailable {
let length = bodyStream.read(&buffer, maxLength: 1024)
if length == 0 {
break
} else {
data.append(&buffer, length: length)
}
}

bodyStream.remove(from: RunLoop.current, forMode: .default)
bodyStream.close()

return data as Data
}

override open func stopLoading()
{
session.getTasksWithCompletionHandler { dataTasks, _, _ in
Expand Down