I’m working with an HTTPBody from a Swift OpenAPI client, and I need to collect the response body into memory. However, both the following approaches result in the same error:
Error: OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once.
- Using ArraySlice(collecting:) to collect the body:
let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024)
- Using a for loop to iterate over the body:
var collectedBytes = Data()
for try await chunk in body {
collectedBytes.append(contentsOf: chunk)
}
Both methods produce the same error, even though the documentation suggests that ArraySlice(collecting:) should be used to collect the full body before processing ().
What I’ve Tried:
- I’ve checked that body is not being iterated over multiple times elsewhere in my code.
- I’ve ensured that the HTTPBody is being consumed only once.
- I’ve followed the documentation regarding usage of ArraySlice(collecting:) to collect the body in a single pass.
Questions:
- What causes the error “HTTPBody attempted to create a second iterator” when using either ArraySlice(collecting:) or for try await chunk in body?
- Is there a way to correctly collect the entire body into a Data object or a similar structure while ensuring I don’t run into this iterator issue?
Here is the surrounding code:
do {
let response = try await client.getGreeting()
print(response)
} catch let error as OpenAPIRuntime.ClientError {
print("Client error - status: \(error.response?.status ?? 0)")
if let body = error.responseBody {
// collect body here
}
} catch {
print("Unexpected error: \(error)")
}