【问题标题】:Alamofire Custom Parameter EncodingAlamofire 自定义参数编码
【发布时间】:2015-08-06 16:06:12
【问题描述】:

我正在使用 Alamofire 并希望使用内容类型“text/html; charset=utf-8”对我的参数进行编码。我按照文档https://github.com/Alamofire/Alamofire 进行自定义参数编码并创建了

let custom: (URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) = {
    (URLRequest, parameters) in
    let mutableURLRequest = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
    mutableURLRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
    mutableURLRequest.body =  // don't know if I need to set this
    return (mutableURLRequest, nil)
}

func postData(){
    Alamofire.request(.POST, baseUrl, parameters: parameters, encoding: .Custom(custom))
        .responseString{ (request, response, data, error) in
    println("blah")
    }
}

当我尝试在我的 Alamofire 请求中使用自定义并收到错误“无法使用类型为 (_, _, _, _)-> _) 的参数列表生成响应字符串时遇到问题但是,这不是如果将编码更改为 .URL 之类的预设,则会出现问题,因此问题似乎出在我的自定义实现中?

如果有影响,我的参数设置在这里:

var parameters = [String: AnyObject]()
func setParams(){
        parameters = [
        "CONTRACT ID" : chosenContract!.iD.toInt()!,
        "FEE AMOUNT" : 0,
        "TRANSACT DATE" : today
    ]
}

【问题讨论】:

  • 你使用的是哪个版本的 Alamofire?,你的代码编译得很好
  • 我使用的是 Alamofire 1.3.0 版

标签: swift encoding alamofire nsmutableurlrequest


【解决方案1】:

您在这里有几个问题。让我们将它们分解为 1x1。

编译器问题

您的编译器问题是由于您的返回元组是错误的类型。在 Alamofire 1.3.0 中,我们将返回类型更改为 NSMutableURLRequest,这最终使事情变得更容易。这应该可以解决您的编译器问题。

设置 HTTPBody

​​>

现在您有几个选择。

选项 1 - 将数据编码为 JSON

let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters!, options: options)

mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data

根据您发布的内容,我假设您实际上想要参数的 .URL 编码。

选项 2 - 使用 .URL 大小写

let parameters: [String: AnyObject] = [:] // fill in
let encodableURLRequest = NSURLRequest(URL: URL)
let encodedURLRequest = ParameterEncoding.URL.encode(encodableURLRequest, parameters).0

let mutableURLRequest = NSMutableURLRequest(URL: encodedURLRequest.URLString)
mutableURLRequest.HTTPMethod = "POST"
mutableURLRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")

Alamofire.request(mutableURLRequest)
         .response { request, response, data, error in
             print(request)
             print(response)
             print(error)
         }

希望这可以帮助您继续前进。祝你好运!

【讨论】:

  • 感谢您的回复!我修复了 NSMutableURLRequest 并且编译器错误消失了。另外,我的编码问题只是对请求如何工作的误解,我真的只需要 .URL
  • 太棒了!如果您认为这是一个足够的答案,那么您应该投票并标记为正确答案。
  • 所以我有一个类似的问题,我无法弄清楚。我正在发送一个 GET 请求,但我的参数格式不正确。这应该是http://dev.plango.us/layout.html#/find-a-plan?selectedPlaces=city:New%20York,state:NY,country:United%20States 的样子,但我得到了http://dev.plango.us/findplans?selectedPlaces=city%3ANew%20York%2Cstate%3ANew%20York%2Ccountry%3AUnited%20States 如何正确设置冒号和逗号的格式?
猜你喜欢
  • 2017-01-27
  • 2017-02-22
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
相关资源
最近更新 更多