swift2 使用Swift 2和PHP将JSON编码为Xcode 7

4xrmg8kj  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(180)

我在let task = session这一行有一个错误,应用程序运行,但当json尝试加载应用程序时停止,并在控制台中显示致命错误:
展开可选值时意外找到nil
我只是尝试显示服务器上的JSON,当我更新到Xcode 7时,这个问题开始出现

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let jsonUrl = "{http://test.yozzibeens.com/AppTesting/JsonArray.php}"

    let session = NSURLSession.sharedSession()
    let shotsUrl = NSURL(string: jsonUrl)

    let task = session.dataTaskWithURL(shotsUrl!)
        {
        (data, response, error) -> Void in

        do {
            let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary

            print(String(jsonData["ip"]!))
        } catch _ {
            // Error
        }
    }

    task.resume()

}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
6vl6ewon

6vl6ewon1#

您需要转义大括号:

let jsonUrl = "{http://test.yozzibeens.com/AppTesting/JsonArray.php}"
let escapeJSONURL = jsonUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

let shotsUrl = NSURL(string: escapeJSONURL)

相关问题