swiftalamofirealamofire-request

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


Solution

  • 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>