1

我目前有一个功能:

  func getJSONDataDictionary (accessToken: String, response: Mappable, url: String) {

    let headers = [
      "Cache-Control": "no-cache",
      "Authorization": "bearer \(accessToken)"
    ]

    Alamofire.request(.GET, url, encoding: .JSON, headers: headers)
      .responseObject{  (response: Response<response, NSError>) in

       let JSONDict = response.result.value

    }
  }

我想为响应参数传入一个类型为 Mappable 的类(该类用于识别一个类是否符合 ObjectMapper 协议)。使用现在的代码方式,我得到一个错误“响应不是类型”。我可以对函数做些什么,所以它需要一个 Mappable 参数?

4

3 回答 3

0

错误消息指出您的参数结果不是类型,但事实并非如此。可映射是一种协议

我建议你让你的函数通用,像这样:

    func getJSONDataDictionary< T: Mappable>(accessToken: String, response: T, url: String) {

    let headers = [
      "Cache-Control": "no-cache",
      "Authorization": "bearer \(accessToken)"
    ]

    Alamofire.request(.GET, url, encoding: .JSON, headers: headers)
      .responseObject{  (response: Response<response, NSError>) in

       let JSONDict = response.result.value

    }
  }

泛型类型T将受限于Mappable协议。

于 2016-11-30T16:46:47.370 回答
0

你可以这样做:

    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = HTTPMethod.post.rawValue
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    let pjson = attendences.toJSONString(prettyPrint: false)
    let data = (pjson?.data(using: .utf8))! as Data

    request.httpBody = data

    Alamofire.request(request).responseJSON { (response) in


        print(response)

    }
于 2017-02-10T14:41:03.990 回答
0
let query_url = Constant.BASE_URL + Constant.ENDPOINT
      var urlRequest = URLRequest(url: URL(string: query_url)!)

      urlRequest.httpMethod = HTTPMethod.get.rawValue
      urlRequest.addValue("Cache-Control", forHTTPHeaderField: "no-cache"")

      urlRequest.addValue("Authorization", forHTTPHeaderField:"bearer \(accessToken)")

      let req = Alamofire.request(urlRequest)
      req.responseObject{ (response: DataResponse<Model>) in
                let value = response.result.value
                print(value?.data?.count)  
            }
于 2018-05-23T05:56:30.283 回答