1 // Copyright 2015-present 650 Industries. All rights reserved. 2 3 import Foundation 4 5 /** 6 `URLRequest.httpBodyData()` extension to read the underlying `httpBodyStream` as Data. 7 */ 8 extension URLRequest { httpBodyDatanull9 func httpBodyData(limit: Int = ExpoRequestInterceptorProtocol.MAX_BODY_SIZE) -> Data? { 10 if let httpBody = self.httpBody { 11 return httpBody 12 } 13 14 if let contentLength = self.allHTTPHeaderFields?["Content-Length"], 15 let contentLengthInt = Int(contentLength), 16 contentLengthInt > limit { 17 return nil 18 } 19 guard let stream = self.httpBodyStream else { 20 return nil 21 } 22 23 let bufferSize: Int = 8192 24 let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize) 25 26 stream.open() 27 defer { 28 buffer.deallocate() 29 stream.close() 30 } 31 32 var data = Data() 33 while stream.hasBytesAvailable { 34 let chunkSize = stream.read(buffer, maxLength: bufferSize) 35 if data.count + chunkSize > limit { 36 return nil 37 } 38 data.append(buffer, count: chunkSize) 39 } 40 41 return data 42 } 43 } 44