iosswiftalamofirealamofire-request

Alamofire Passing Parameter With following type


enter image description here

How to send this data as parameter in alamofire request as parameter?

What I'm doing is:

enter image description here

Requesting Service:

enter image description here

I'm getting this:

enter image description here

I Supposed to get this by sending following way of data:

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>