Class does not conform to protocol RequestRetrier

最后都变了- 提交于 2019-12-11 05:42:30

问题


I have been migrating my project to swift3 and have been battling to get Alamofire RequestRetrier protocol to work. I have followed Alamofire 4.0 migrating guide: https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md#request-retrier

This is the class I'm trying to build:

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
        }
    }

}

Building fails with the following error: Type 'RequestAccessTokenAdapter' does not conform to protocol 'RequestRetrier'

I have been trying with both Alamofire 4.2.0 & AlamofireObjectMapper 4.0.1 and also with Alamofire 4.0.1 & AlamofireObjectMapper 4.0.0 but I keep getting the same error.

Everything builds ok if I only use RequestAdapter protocol and remove should-function, but I can't seem to get the RequestRetrier to build, which I also need for my project.

Any idea what I'm missing from my class?

EDIT:

I seemed to have a namespace issue as the code build succeeded after I replaced Error with Swift.Error in the definition of should-function:

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

回答1:


I too was seeing the same issue. After having a look at the Alamofire source code, I found that XCode is auto-generating an invalid method signature for the should method. By explicitly adding the Alamofire module name to the SessionManager, Request and RequestRetryCompletion type declarations, in the should method's argument list, I was finally able to get this to build. So, your should method should look something like this:

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

    // Do something

}

I hope this helps!



来源:https://stackoverflow.com/questions/40926681/class-does-not-conform-to-protocol-requestretrier

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!