swift - Alamofire 请求链接 - 无法调用非函数类型的值 'HTTPURLResponse'

标签 swift alamofire swift4

这里有一个新的 Swift 人。我正在尝试弄清楚如何将多个 Alamofire 调用链接在一起。

我需要

  1. 从服务器 1 获取授权 token
  2. 从服务器 1 获取一些数据(需要授权 token )
  3. 从服务器 2 获取授权 token
  4. 根据第 2 步中的值从服务器 2 获取更多数据。

我已经尝试按照这篇文章中的示例进行操作: Chain multiple Alamofire requests

不幸的是,这些示例都不适用于 Swift 4。

我已经决定采用选项 2,但会不断得到一个

Cannot call value of non-function type 'HTTPURLResponse?'

putRequestgetRequest 行都出错。我不知道这意味着什么或如何解决它。

我当前的代码:

import UIKit
import PromiseKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController {

    let URL = "http://httpbin.org/"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func runPutRequest() {

        let putRequest = Alamofire.request("\(URL)/get")

        putRequest.response { [weak self] putRequest, putResponse, putData, putError in
            if let strongSelf = self {
                // Probably store some data
                strongSelf.runGetRequest()
            }
        }
    }

    func runGetRequest() {

        let getRequest = Alamofire.request("\(URL)/get", method: .get)

        getRequest.response { [weak self] getRequest, getResponse, getData, getError in
            if let strongSelf = self {
                // Probably store more data
                strongSelf.processResponse()
            }
        }
    }

    func processResponse() {
        // Process that data
    }

    func reloadData() {
        // Reload that data
    }
}

如有任何帮助,我们将不胜感激。

最佳答案

对于 response 闭包,您有太多的返回参数,实际上您只需要一个 DataResponse 参数。这段代码对我有用:

func runPutRequest() {
    let putRequest = Alamofire.request("\(URL)/get", method: .put)
    putRequest.response { [weak self] response in
        if let strongSelf = self {
            // Probably store some data
            strongSelf.runGetRequest()
        }
    }
}

func runGetRequest() {
    let getRequest = Alamofire.request("\(URL)/get", method: .get)
    getRequest.response { [weak self] response in
        if let strongSelf = self {
            // Probably store more data
            strongSelf.processResponse()
        }
    }
}

关于swift - Alamofire 请求链接 - 无法调用非函数类型的值 'HTTPURLResponse',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46574793/

相关文章:

ios - Swift Var 中使用的数据结构和 var 到类型的内部映射

ios - 迦太基解析错误

ruby-on-rails - Devise_token_auth - 无法运行 Controller 操作

swift - url 路径中的 Alamofire 变量或参数支持

ios - 如何解决此错误: Could not cast value of type '__NSCFString' (0x10354a248) to 'UIImage' (0x104c42b48)

ios - Swift 协议(protocol) Where Constraint with == vs :

ios - 没有从纬度和经度获得正确的地址

swift - 排序字典类型 [String :any]

ios - 如何使用 RxAlamofire 取消之前的请求?

arrays - 在 Swift 4 中复制 NSManagedObject 对象数组