gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:48:34 25 4
gpt4 key购买 nike

我是IOS开发新手,刚开始接触swift语言。

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

让我们假设两个文本字段是- 姓名- 通过

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

最佳答案

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

Swift 4 及更高版本

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

关于ios - 如何使用swift语言创建json数据并将其发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27654550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com