无法获取路径Swift playground错误的沙箱扩展

时间:2017-10-22 21:19:31

标签: json swift xcode api swift-playground

我正在尝试使用JSON解析API中的数据并收到以下错误:

Failed to obtain sandbox extension for path=/var/folders/4g/g8pv7pms3_n7grf2y7db_dx00000gn/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.testJSON-CB872E50-7C0F-4640-9B40-BA0EFE9BFA44/Library/Caches/com.apple.dt.playground.stub.iOS_Simulator.testJSON-CB872E50-7C0F-4640-9B40-BA0EFE9BFA44.

我的代码如下:

let url = URL(string: "http://engine.hotellook.com/api/v2/static/hotels.json?locationId=895&token=6251c90d5bc52c88b60a38bd84373513")

let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
    print("IN?")
    if error != nil {
        print ("ERROR")
    }
    else {
        print("Check2")
        if data != nil {
            do {
                //Array
                let myJson = try? JSONSerialization.jsonObject(with: data!, options: [])
                if let dictionary = myJson as? [String: Any] {
                    print(dictionary.description)           
                }
            }
        }
    }
}
task.resume()

1 个答案:

答案 0 :(得分:1)

您需要导入PlaygroundSupport并将当前页面的needsIndefiniteExecution设置为true:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

除此之外,您还应该做一些改进代码的事情:

URLSession.shared.dataTask(with: url) { (data, response, error) in
    guard let data = data, error == nil else {
        return
    }
    do {
        let dictionary = try JSONSerialization.jsonObject(with: data) as? [String: Any] ?? [:]
        print(dictionary)
    } catch {
        print(error)
    }
}.resume()