gpt4 book ai didi

json - 如何在 swift 中使用 json 进行 HTTPRequest

转载 作者:行者123 更新时间:2023-11-28 14:57:09 25 4
gpt4 key购买 nike

我正在制作一个 ios 应用程序。我是 swift 的新手,无法理解我的代码。任何人都可以帮助我了解我的代码发生了什么。

这是添加电子邮件 ID 的登录应用程序,如果电子邮件存在,它应该转到下一个 View Controller ,如果不存在,那么它应该给出错误。我越来越难以理解我的代码。

这是我的代码:

class checkLoginViewController: UIViewController {

@IBOutlet weak var checkUsernametextfield: UITextField!

@IBAction func checkUsernameButton(_ sender: UIButton) {
print("Clicked On SUbmit !!!!")

//Read Value from Text
let email = checkUsernametextfield.text
let myUrl = URL(string: "http://192.168.0.117/rest/signup.php");

var request = URLRequest(url:myUrl!)

request.httpMethod = "POST"// Compose a query string

let postString = "email=\(String(describing: email))";

request.httpBody = postString.data(using: String.Encoding.utf8);

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
// You can print out response object
print("response = \(String(describing: response))")

//Let's convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
// Now we can access value of First Name by its key
let emailValue = parseJSON["email"] as? String
print("email: \(String(describing: emailValue))")
}
} catch {
print(error)
}
}
task.resume()

输出:

Clicked On SUbmit !!!! response = Optional( { URL: http://192.168.0.117/rest/signup.php } { Status Code: 200, Headers { Connection = ( "Keep-Alive" ); "Content-Length" = ( 61 ); "Content-Type" = ( "application/json" ); Date = ( "Mon, 12 Mar 2018 06:35:58 GMT" ); "Keep-Alive" = ( "timeout=5, max=100" ); Server = ( "Apache/2.4.27 (Ubuntu)" ); } }) email: nil

最佳答案

也许试试这个。希望它有效。

  let url = URL(string:"http://192.168.0.117/rest/signup.php")
let parameters = ["email": checkUsernametextfield.text]
var request = URLRequest(url : url!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject:parameters, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let session = URLSession.shared
session.dataTask(with: request, completionHandler: { (data, response, error) in
if let data = data {
do {
let json = try? JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
if let json = json {
print("HERE SHOULD BE YOUR JSON \(json)")
}
}
} else {
print("Error \(String(describing: error?.localizedDescription))")
}
}).resume()

关于json - 如何在 swift 中使用 json 进行 HTTPRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49231926/

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