如何使用Swift语言创建JSON数据并将其发送到服务器 [英] How to create and send the json data to server using swift language

查看:171
本文介绍了如何使用Swift语言创建JSON数据并将其发送到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是IOS开发的新手,我已经开始使用敏捷的语言了.

I'm new to IOS development and I have started with the swift language.

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

I'm trying to get the value from two text fields and convert those two text fields into json and send that json to the server receive.php.

让我们考虑到拖曳文本字段是 - 姓名 -通过

lets concider that tow text fields are - name - pass

我如何创建Json& ;?单击按钮时将其发送到服务器吗?

how do i create a Json & send that to server when a button is clicked ?

推荐答案

通过将HTTP POST方法与NSURLSession一起使用.假设您正在按登录按钮

By using http POST method with NSURLSession. Let's say you are calling submitAction method on the press of the login button

快捷键3

@IBAction func submitAction(_ sender: UIButton) {

    //declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid

    let parameters: [String: String] = ["name": nametextField.text, "password": passwordTextField.text]

    //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, 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()
}

这篇关于如何使用Swift语言创建JSON数据并将其发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆