如何在swift中将json转换为字节格式?

时间:2016-09-14 15:21:11

标签: ios json swift post login

我正在开发一个应用程序,它将获取用户名和密码,对其进行身份验证并将其登录。所以我正在做的是获取输入并将它们转换为JSON。但在我发送它之前,它们需要采用字节格式才能工作。

到目前为止,这就是我所拥有的。

@IBOutlet var name: UITextField!
@IBOutlet var password: UITextField!


let json: [String: AnyObject] = ["name:": name.text! as AnyObject,
                                     "password:": password.text! as AnyObject]

    do{

        let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)

        //this is just an example website
        let url = URL(string: "https://example.com")

        let request = NSMutableURLRequest(url: url!)

        request.httpMethod = "POST"

        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request as URLRequest) {(data, response, error) in

            guard error == nil else {
                print(error)
                return
            }

            let JSON = try! JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)

            print(JSON)
        }

        task.resume()

        } catch {
            print(error)
        }

我知道有一些叫做JSON封送的东西但不确定Swift中是否存在这种东西。

如何在Swift中将JSON文件转换为字节格式?

0 个答案:

没有答案