Deploying a Vapor app to Heroku fails because of " error: value of type 'URLSession' has no member 'data' "

Deploying a Vapor app to Heroku fails because of " error: value of type 'URLSession' has no member 'data' "

我使用 Vapor 创建了一个应用程序,我想将它部署到 Heroku,但是推送失败。

构建配置如下所示

日志如下所示。

remote: Compressing source files... done.
remote: Building source:
remote: 
remote: -----> Building on the Heroku-20 stack
remote: -----> Using buildpack: https://github.com/vapor-community/heroku-buildpack
remote: -----> Swift app detected
remote: -----> Using Swift 5.5 (from .swift-version file)
remote: -----> Using built-in clang (Swift 5.5)
remote: -----> Installing swiftenv
remote: -----> Installing Swift 5.5
remote: Downloading https://swift.org/builds/swift-5.5-release/ubuntu2004/swift-5.5-RELEASE/swift-5.5-RELEASE-ubuntu20.04.tar.gz
remote: /tmp/swiftenv-5.5- /tmp/codon/tmp/buildpacks/66275d05cfaec82f8023e1ae68b013a22671c52f

.
.
.

remote: /tmp/build_ecf900fb/Sources/App/APIClient/APIClient.swift:61:34: error: value of type 'URLSession' has no member 'data
remote:         return try await session.data(for: request, delegate: nil)
remote:                          ~~~~~~~ ^~~~
remote: /tmp/build_ecf900fb/Sources/App/APIClient/APIClient.swift:61:63: error: 'nil' requires a contextual type
remote:         return try await session.data(for: request, delegate: nil)
remote:                                                               ^
remote:  !     Push rejected, failed to compile Swift app.
remote: 
remote:  !     Push failed
remote: Verifying deploy...
remote: 
remote: !   Push rejected to apple-dev-news-ios.
remote: 
To https://git.heroku.com/apple-dev-news-ios.git
 ! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/apple-dev-news-ios.git'

APIClient.swift:61:63:

    private let session: URLSession

    .
    .
    .

    private func actuallySend(_ request: URLRequest) async throws -> (Data, URLResponse) {
        .
        .
        .
        return try await session.data(for: request, delegate: nil)
    }

为什么会失败,我们怎样才能使推送成功?

'data'在Foundation框架中定义如下

@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
extension URLSession {

    /// Convenience method to load data using an URLRequest, creates and resumes an URLSessionDataTask internally.
    ///
    /// - Parameter request: The URLRequest for which to load data.
    /// - Parameter delegate: Task-specific delegate.
    /// - Returns: Data and response.
    public func data(for request: URLRequest, delegate: URLSessionTaskDelegate? = nil) async throws -> (Data, URLResponse)
.
.
.

Linux 上的 Foundation 异步 API 尚不可用(它们不同于实际的语言并发功能)。

对于 Vapor 应用程序,您实际上不应该使用 URLSession 来发出请求,它不符合框架的工作方式。请改用 Vapor 的 client(它具有异步 API)