Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

swift - Alamofire parameter with multiple values in one Key

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

data : {"username":"username","password":"password"}

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

what I'm doing is:

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

Alamofire.request(loginUrl, method: .post, parameters: parameter,encoding: JSONEncoding.default, headers: nil).responseJSON { response in

but it is not working.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Create data params:

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

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
]

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 ""
}

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...