ios - JSON 数据返回 nil

标签 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)
                }
            }

        }

View Controller

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. 

有什么理由吗?

最佳答案

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

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

关于ios - JSON 数据返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40373504/

相关文章:

ios - 如何使用 Titanium 检索用户的 iOS 版本

ios - 如何在 ios 中提取隐藏的输入 uiwebview?

iphone - 如何更改 PhoneGap 1.x 中的起始页

javascript - 如何列出 Typeahead.js 和/或 Bloodhound 引擎的对象?

javascript - 在 Postman 中导入外部库

iOS:UISearchBar 显示为有色

ios - Hello World VR 应用

java - JsonSyntaxException - 预期为 BEGIN_OBJECT,但实际为 BEGIN_ARRAY

ios - 将数据从我的 viewcontroller 类传递到放置在同一场景中的自定义类 UIView 时,“包装可选值时出现意外的 nil”

swift - 将 SwiftUI View 转换为 NSImage