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

标签 json swift

我正在制作一个 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/

相关文章:

javascript - Rails 4 - ajax 不起作用,我需要刷新页面

android - Retrofit 2.0 转换器返回 NULL

asp.net - 为 Web API 操作设置默认媒体格式化程序

ios - 错误 :'inout IndexPath' 不可转换为 'IndexPath'

ios - UITableview 页脚在向下滚动时刷新?

swift - 在 Swift 中,对一组 UIView 进行动画处理以使其在 StackView 中依次出现的最佳方法是什么?

json - 如何使用Json4s将Map转Json

javascript - JSON.parse 中 JSON 中位置 0 处出现意外标记 <

swift - SIGABRT with coredata uncaught exception of type NSExeption

ios - 从 Facebook JSON 访问好友数据