字符0 swift

时间:2017-07-26 15:57:24

标签: ios json swift

我希望你过得愉快。我遇到了一个错误,我做了一些研究。我认为错误意味着我的JSON对象不是由swift 3.0上的JSONSerialization类序列化的正确对象。我通过使用JSONSerialization类的.isValidJSONObject方法验证了我的json对象无效。

我检查了我的json对象是否有效。在执行“JSONSerialization.jsonObject”方法的行发生错误。我很乐意,如果你能帮我弄清楚如何解决这个问题。随意请求更多代码部件或项目设置。提前致谢。

以下是使用的代码:

import UIKit

class ViewController: UIViewController, NSURLConnectionDataDelegate {
    lazy var receivedData = NSMutableData()

    override func viewDidLoad() {
        super.viewDidLoad()
        var url = NSURL(string:"http://localhost:8080/OurServer/webresources/server")!
        var request = NSURLRequest(url: url as URL)
        var connection = NSURLConnection(request: request as URLRequest, delegate: self, startImmediately: false)!
        connection.start()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func connection(_ connection: NSURLConnection, didReceive data: Data)
    {
        receivedData.append(data)
        var temp1 = receivedData as NSMutableData
        do
        {
            var temp3 = JSONSerialization.isValidJSONObject(receivedData)
                var jsonResult = try JSONSerialization.jsonObject(with: receivedData as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary

            print("\n")
            print(jsonResult)
        }
        catch let error as NSError
        {
            print("\n" + "\(error)")
        }
    }
}

2 个答案:

答案 0 :(得分:1)

正如评论中所提到的NSURLConnection已过时。

这是使用URLSession

的代码的现代Swift 3兼容版本
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string:"http://localhost:8080/OurServer/webresources/server")!
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }
            do {
                let jsonResult = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
                print("\n", jsonResult)
            } catch {
                print("\n", error)
            }
        }
        task.resume()
    }
}

答案 1 :(得分:0)

检查后,看起来我犯了一个不太聪明的错误。错误在于我的网址。请原谅我。