如何在Alamofire中使用POST命令发送这个JSON对象?

时间:2017-02-13 06:27:04

标签: ios json swift alamofire

我从iOS应用中的文本框中提取了两个字段,我想将以下JSON对象发送回服务器。(使用AlamoFire)当用户输入用户名和密码时,应该发送此数据作为JSON对象返回服务器。 我应该如何编写用于发送此特定JSON对象的POST方法? 我的JSON如下:

   { "settings": 
       {
          "username": "myUserName",
          "password": "myPassword123"
       }
   }

这是我在Swift 3中的课程,

class logIN {

    let username: String! = nil
    let password: String! = nil

init(ssid: String, password: String) {

    let parameters: [String: String] = [
            "username": ssid as String,
            "password": password as String
        ]

    var statusCode: Int = 0
    Alamofire.request("URL_HERE", parameters: parameters)
        .responseJSON { response in
            statusCode = (response.response?.statusCode)! 
            print(String(statusCode))

        }
    }
}

这是我完成按钮的IBAction,单击此按钮将发送POST请求。

@IBAction func doneButton(_ sender: Any) {
    let logInInstance = logIN(ssid : self.username.text!, password : self.password.text!)

}

1 个答案:

答案 0 :(得分:2)

    let loginParam: [String: String] = [
                "username": ssid as String,
                "password": password as String
            ]

    var parameters = [String:Any]()
    parameters["setting"] = loginParam

    var statusCode: Int = 0
    Alamofire.request("URL_HERE", parameters: parameters)
        .responseJSON { response in
            statusCode = (response.response?.statusCode)! 
            print(String(statusCode))

        }
    }