一个按键中具有多个值的Alamofire参数 [英] Alamofire parameter with multiple values in one Key

查看:110
本文介绍了一个按键中具有多个值的Alamofire参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将参数作为以下数据的alamofire参数发送?

How to send parameter as alamofire parameter for the following data?

data:{ username: username, password ::密码}

我想通过alamofire参数实现关注,但我没有做到这一点。

I want to achieve following through alamofire paramter, but I failed to achieve this.

我正在做的是:

let参数:参数= [数据:[用户名 : \(textFieldUserName.text!), pass: \(textFieldPassword.text!)]]

Alamofire.request(loginUrl,方法:.post,参数:参数,编码:JSONEncoding.default,标头:nil).responseJSON {
响应

,但不起作用。

推荐答案

在查看您使用的api之后:api期望数据值是一个字符串,而不是一个对象。
您需要执行以下操作:但这可以重构为更加简洁,这只是为了说明发生了什么。

After taking a look at the api you're using: The api expects for the data value to be a string and not an object. You'll need to do something like this: But this can be refactored to be much cleaner, this is just to explain whats going on.

创建数据参数:

let data: Parameters = [
    "username": "\(textFieldUserName.text!)",
    "pass": "\(textFieldPassword.text!)"
]

然后将其转换为字符串:下面是将json转换为字符串的快速搜索,但是在我得到第一个答案时,您需要仔细检查一下。

then convert it to a string: below is a quick search to convert json to string, but you'll need to double check that, as I took the first answer.

let string = stringify(json: data, prettyPrinted: false)

let parameters: Parameters = [
    "data": string
]

,然后在请求中将编码设置为: encoding:URLEncoding .default

and in the request set the encoding to: encoding: URLEncoding.default

Alamofire.request(
        loginURL,
        method: .post,
        parameters: parameters,
        encoding: URLEncoding.default,
        headers: nil).responseJSON { (responseData) -> Void in
            if responseData.result.value != nil {
                //do something with data
    }
}

func stringify(json: Any, prettyPrinted: Bool = false) -> String {
    var options: JSONSerialization.WritingOptions = []
    if prettyPrinted {
        options = JSONSerialization.WritingOptions.prettyPrinted
    }

    do {
      let data = try JSONSerialization.data(withJSONObject: json, options: options)
      if let string = String(data: data, encoding: String.Encoding.utf8) {
          return string
      }
    } catch {
          print(error)
    }
    return ""
}

我也将尝试避免强行打开textfield.text属性,除非您在
之前验证它们的值,并且由于api调用是http,您还需要在info.plist中启用该功能:

I would also try to avoid force unwrapping the textfield.text properties, unless you're validating their values somewhere else before hand and since the api call is http, you also need to enabled that in info.plist:

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

这篇关于一个按键中具有多个值的Alamofire参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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