Swift 3.0迁移后的Alamofire错误:“Call'中的额外参数”(请求方法)

时间:2016-10-05 16:31:35

标签: ios swift3 alamofire

我目前正在将我的代码库更新为Swift 3.0,我正在使用Alamofire。
因此,我不得不将Alamofire更新为4.0(Alamofire git repo)。
我有一个请求从服务器获取数据的方法,在迁移之前,它运行得非常好。
使用Xcode的迁移工具后,我最终得到了这个错误:"Extra argument in Call"
我&#39 ;我不太清楚为什么这种方法不再有效。
任何帮助都会很精彩!

class func makeRequest(
    _ method: RequestMethod,
    authorization: String?,
    uri: String,
    params: JSONDictionary?,
    retry: Bool = true,
    completionHandler: @escaping RequestCompletionBlock)
{

    let requestURL = baseURL + uri
    let authHeader: Dictionary<String, String>? = authorization != nil ? ["Authorization" : authorization!] : nil

    //requestURL is highlighted, says "Extra argument in call"
    sharedAlamofireManager.request(Method(rawValue: method.rawValue)!, requestURL, parameters: params, encoding: .JSON, headers: authHeader).responseJSON {
        response in

    }
}

Migration Guide for Alamofire4.0

编辑:JSONDictionary:

typealias JSONDictionary = Dictionary<String, Any>

sharedAlamoFireManager也是一个SessionManager

1 个答案:

答案 0 :(得分:2)

Per AlamoFire docs The RequestAdapter protocol is a completely new feature in Alamofire 4. It allows each Request made on a SessionManager to be inspected and adapted before being created. One very specific way to use an adapter is to append an Authorization header to requests behind a certain type of authentication.

标头不再是请求方法的参数,而是设置在请求适配器内。

首先我必须创建AccessTokenAdapter类:

class AccessTokenAdapter: RequestAdapter {
    private let accessToken: String

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

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

        if urlRequest.urlString.hasPrefix(RequestManager.returnBaseURL()) {
            urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
        }

        return urlRequest
    }
}

然后我需要更新我的方法:

class func makeRequest(
    _ method: RequestMethod,
    authorization: String?,
    uri: String,
    params: JSONDictionary?,
    retry: Bool = true,
    completionHandler: @escaping RequestCompletionBlock)
{

    let requestURL = baseURL + uri
    var accessToken: String?
    if let authorization = authorization {
        accessToken = authorization
    }else{
        accessToken = self.token()!
    }

    sharedAlamofireManager.adapter = AccessTokenAdapter(accessToken: accessToken!)

    sharedAlamofireManager.request(requestURL, method: .get, parameters: params, encoding: JSONEncoding.default)
        .responseJSON { response in

    }
}