JSON数据返回nil

时间:2016-11-02 06:11:29

标签: ios json swift

我从我的服务器获取数据,并尝试将其转换为JSON。在我的PHP脚本上,我将其转换为JSON,然后将其发送。

这是我的代码:

let url: NSURL = NSURL(string: "https://xxxxxx.com/myFile.php")!
        let request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
        let bodyData = "username=\(username.text!)&password=\(password.text!)"
        request.httpMethod = "POST"
        request.httpBody = bodyData.data(using: String.Encoding.utf8);
        request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
        NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main)
        {
            (response, data, error) in
            if(error == nil){
                var responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

                DispatchQueue.main.async {
                    let viewController = self.storyboard?.instantiateViewController(withIdentifier: "nextVC") as! ViewController
                    viewController.importData = data!
                    viewController.modalTransitionStyle = .crossDissolve
                    self.present(viewController, animated: true, completion: nil)
                }
            }

        }

的ViewController

var importData = Data() //when I cast this to NSString and print it I see the JSON correctly.
let json = JSON(data: importData) //  this prints nil. 

有什么理由?

1 个答案:

答案 0 :(得分:0)

尝试将响应转换为字符串,并查看服务器的响应是否有效。

var dataString = String(data: importedData, encoding: .utf8)
print(dataString)