Alamofire请求的多种编码类型 [英] Multiple encoding types for Alamofire Request

查看:85
本文介绍了Alamofire请求的多种编码类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用带有 JSON 对象的HTTP正文发出 POST 请求,但是我还需要在同一请求中使用url查询参数。

I need to make a POST request with an HTTP Body with a JSON object, but I also need to use url query parameters in the same request.

POST: http://www.example.com/api/create?param1=value&param2=value
HTTP Body: { foo : [ bar, foo], bar: foo}

Alamofire支持吗?我将如何去做呢?

Is this supported by Alamofire? How would I go about doing this?

推荐答案

这绝对是一个有效的用例。我尝试将访问令牌作为查询参数附加到POST请求时遇到了类似的问题。这是一个应该暂时使事情变得简单的函数,类似于您的方法。

This is definitely a valid use case. I've ran into similar issues with trying to append access tokens as query parameters to a POST request. Here's a function that should make things a bit easier for the time being that is similar to your approach.

func multiEncodedURLRequest(
    method: Alamofire.Method,
    URLString: URLStringConvertible,
    URLParameters: [String: AnyObject],
    bodyParameters: [String: AnyObject]) -> NSURLRequest
{
    let tempURLRequest = NSURLRequest(URL: NSURL(string: URLString.URLString)!)
    let URLRequest = ParameterEncoding.URL.encode(tempURLRequest, parameters: URLParameters)
    let bodyRequest = ParameterEncoding.JSON.encode(tempURLRequest, parameters: bodyParameters)

    let compositeRequest = URLRequest.0.mutableCopy() as NSMutableURLRequest
    compositeRequest.HTTPMethod = method.rawValue
    compositeRequest.HTTPBody = bodyRequest.0.HTTPBody

    return compositeRequest
}

话虽如此,您能否确定在 Github 上添加功能请求问题?这肯定是我们需要弄清楚的方法,因为它是一种常见的用例,因此在Alamofire中如何使它变得更容易。如果您可以对用例进行很好的描述,那么我相信它将引起关注。我一定会帮助媒体获得更多支持。

With that said, could you make sure to put in a feature request issue on the Github? This is certainly something we need to figure out how to make easier in Alamofire since it's such a common use case. If you could put in a really good description of your use case, then I'm sure it will get attention. I will certainly help press to get support added.

这篇关于Alamofire请求的多种编码类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆