类不符合协议RequestRetrier

lii*_*one 1 alamofire swift3

我一直在将我的项目迁移到swift3,并一直在努力让Alamofire RequestRetrier协议工作.我关注了Alamofire 4.0迁移指南:https: //github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md#request-retrier

这是我正在尝试构建的类:

import Foundation
import Alamofire

class RequestAccessTokenAdapter: RequestAdapter, RequestRetrier {
    private let accessToken: String

    init(accessToken: String) {
        self.accessToken = accessToken
    }

    func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
        var urlRequest = urlRequest

        if (urlRequest.url?.absoluteString.hasPrefix(MyServer.serverUrl()))! {
            urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
        }

        return urlRequest
    }

    func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {
        if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 {
            completion(true, 1.0) // retry after 1 second
        } else {
            completion(false, 0.0) // don't retry
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

构建失败并出现以下错误:类型"RequestAccessTokenAdapter"不符合协议"RequestRetrier"

我一直在尝试使用Alamofire 4.2.0和AlamofireObjectMapper 4.0.1以及Alamofire 4.0.1和AlamofireObjectMapper 4.0.0但我仍然遇到同样的错误.

如果我只使用RequestAdapter协议并删除should-function,那么一切都可以构建好,但是我似乎无法构建RequestRetrier,这也是我的项目所需要的.

知道我班上缺少什么吗?

编辑:

我似乎有一个命名空间问题,因为代码构建成功后我在should-function的定义中用Swift.Error替换了Error:

func should(_ manager: SessionManager, retry request: Request, with error: Swift.Error, completion: @escaping RequestRetryCompletion) {
Run Code Online (Sandbox Code Playgroud)

Tim*_*ore 8

我也看到了同样的问题.看了Alamofire源代码之后,我发现XCode会自动为该should方法生成一个无效的方法签名.通过明确添加Alamofire模块名到SessionManager,RequestRequestRetryCompletion类型声明,在should方法的参数列表,我终于能够得到这个建立.所以,你的should方法应该是这样的:

func should(_ manager:      Alamofire.SessionManager,
            retry request:  Alamofire.Request,
            with error:     Error,
            completion:     @escaping Alamofire.RequestRetryCompletion) {

    // Do something

}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!

  • 谢谢你的回答.它帮助我解决了我的问题.我可能有某种命名空间冲突,但当我用Swift.Error替换Error时,我的代码构建成功了. (2认同)