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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27654550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:08:29  来源:igfitidea点击:

How to create and send the json data to server using swift language

iosjsonswiftxcode6swift-playground

提问by Uday

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

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

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.

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

lets concider that tow text fields are - name - pass

让我们考虑两个文本字段是 - 名称 - 通过

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

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

回答by Suhit Patil

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

通过使用带有 NSURLSession 的 http POST 方法。假设您在按下登录按钮时调用 submitAction 方法

Swift 3

斯威夫特 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()
}

回答by Kingsley Mitchell

Swift 3,Swift 4 The method above is very in-efficient, use alamofire instead

Swift 3,Swift 4 上面的方法效率很低,改用alamofire

https://github.com/Alamofire/Alamofire

https://github.com/Alamofire/Alamofire

get email and passwoord from textfield

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

@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) }

or here is an example

或者这里是一个例子

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