Swift JSON解析用户名和密码

时间:2017-01-16 20:58:30

标签: ios json swift

我正在尝试POST用户名&密码为NSDictionary,通过JSON格式。我收到以下错误:

  

Domain = NSCocoaErrorDomain Code = 3840“
  JSON文本不以数组或对象和选项开头,以允许未设置片段。“
  UserInfo = {NSDebugDescription = JSON文本不以数组或对象开头,并且选项允许未设置片段。}

我的代码如下:

@IBAction func loginAuthentication(_ sender: UIButton) {
    let username : NSString = NameTextField.text! as NSString
    let password : NSString = passwordTextField.text! as NSString

    let parameters = [
        "username": "\(username)",
        "password": "\(password)"
    ]
    print(parameters)

    let headers = [
        "content-type": "application/json",
        "cache-control": "no-cache",
        "postman-token": "121b2f04-d2a4-72b7-a93f-98e3383f9fa0"
    ]

        if let postData = (try? JSONSerialization.data(withJSONObject: parameters, options: [])) {

        let request = NSMutableURLRequest(url: URL(string: "http://..")!,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = postData

        print(request.httpBody)

       // let session = URLSession.shared

        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            (data, response, error) -> Void in
                    if (error != nil) {
                                        print("Error message \(error)")

                                        } else {
                    DispatchQueue.main.async(execute: {

                                        if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? NSDictionary
                                        {
                                            let success = json["error"] as? Bool

                                            print("Error from php\(success)")

                                            let message = json["message"] as? String
                                                // here you check your success code.
                                                if (success == false)
                                                        {
                                                        print("Result1 \(message)")
                                                        self.performSegue(withIdentifier: "", sender: self)
                                                        }
                                                else
                                                        {
                                                            self.dismiss(animated: true, completion: nil)
                                                            print("Result2 \(message)")
                                                        }

                                        }

                                        })
                                }
        }

        task.resume()
}
}

1 个答案:

答案 0 :(得分:0)

问题在于我,因为您的字符串未正确序列化。而不是当前的json序列化方法,只需将swift字典转换为数据。

//Start with a dictionary
let body = [
    "username": "bob",
    "password": "admin"
]
//Serialize it.... you might want to put this in a do try catch block instead
let jsonBody = try? JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
//Add it to the request
request.httpBody = jsonBody

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