如何使用swift语言创建json数据并将其发送到服务器

时间:2014-12-26 08:10:59

标签: ios json swift xcode6 swift-playground

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

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

让两个文本字段的concider - 名称 - 传递

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

2 个答案:

答案 0 :(得分:22)

通过NSURLSession使用http POST方法。我们假设您在按下登录按钮

时调用了submitAction方法

Swift 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()
}

答案 1 :(得分:0)

雨燕3,雨燕4 上面的方法效率很低,请改用alamofire

https://github.com/Alamofire/Alamofire

从文本字段获取电子邮件和密码

@IBAction func submitAction(sender: AnyObject) {
let email= emailfield.text
let password= emailfield.text
let parameters: Parameters = [
    "email": email,
    "password": password
    ]

Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters) }

或者这是一个例子

let parameters: Parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
    "x": 1,
    "y": 2,
    "z": 3
]
]

// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)

// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3