如何使用swift语言创build和发送json数据到服务器

我是IOS开发新手,我已经开始使用迅速的语言。

我试图从两个文本字段中获取值,并将这两个文本字段转换为json,然后将该json发送到服务器receive.php。

让那个拖拽文本字段为 – 名称的concider通过

如何创build一个Json&发送到服务器,当一个button被点击?

通过使用NSURLSession的http POST方法。 假设您在loginbutton的按下时调用了submitAction方法

Swift 3

@IBAction func submitAction(sender: AnyObject) { //declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid let parameters = ["name": nametextField.text, "password": passwordTextField.text] as Dictionary<String, String> //create the url with URL let url = URL(string: "http://myServerName.com/api")! //change the url //create the session object let session = URLSession.shared //now create the URLRequest object using the url object var request = URLRequest(url: url) request.httpMethod = "POST" //set http method as POST do { request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body } catch let error { print(error.localizedDescription) } request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") //create dataTask using the session object to send data to the server let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in guard error == nil else { return } guard let data = data else { return } do { //create json object from data if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] { print(json) // handle json... } } catch let error { print(error.localizedDescription) } }) task.resume() }