具有自定义参数编码的 Alamofire 用于快速应用程序

Posted

技术标签:

【中文标题】具有自定义参数编码的 Alamofire 用于快速应用程序【英文标题】:Alamofire with custom parameter encoding for swift application 【发布时间】:2014-10-31 23:09:27 【问题描述】:

我必须在我的swift应用程序中调用soap web服务中的一些方法,所以我认为我应该使用自定义参数编码,但是当我为这个编码创建闭包时,它似乎永远不会被调用。我做错了吗?

这是我的代码:

    let custom: (URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?) = 
        (URLRequest, parameters) in
        let mutableURLRequest = URLRequest.URLRequest.mutableCopy() as NSMutableURLRequest
        mutableURLRequest.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        mutableURLRequest.HTTPBody = body
        return (mutableURLRequest, nil)
    

    Alamofire.request(.POST, WebServiceURLString, parameters: nil, encoding: .Custom(custom)).responseString  (request, response, data, error) -> Void in
        println(data)
    

【问题讨论】:

【参考方案1】:

custom 闭包不是按设计执行的,因为没有要编码的参数。他是摘自Alamofire.swift source file的代码:

if parameters == nil 
    return (URLRequest.URLRequest, nil)

如您所见,您可以通过传递一个空字典来绕过此条件:

Alamofire.request(.POST, WebServiceURLString, parameters: Dictionary(), encoding: .Custom(custom))

custom 闭包现在将被执行。

【讨论】:

空字典不会在最新的 Alamofire 中使用。参数必须包含至少一个键/值对才能执行自定义闭包。 "守卫让参数 = 参数 where !parameters.isEmpty"

以上是关于具有自定义参数编码的 Alamofire 用于快速应用程序的主要内容,如果未能解决你的问题,请参考以下文章

Moya/Alamofire - 具有相同键的 URL 编码参数

Alamofire 发送带键和多值的参数数组

swift 具有Argo和自定义错误类型的Generic Alamofire响应序列化程序

如何在 Alamofire 中为 GET 方法发送自定义参数?

Swift - 使用 alamofire 发布请求

Alamofire JSON 编码布尔问题?