最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

swift - Error: “HTTPBody attempted to create a second iterator” when collecting body using ArraySlice(collecting:) and iterating

programmeradmin2浏览0评论

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.
  1. Using ArraySlice(collecting:) to collect the body:
let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024)
  1. 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)")
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论