json - 无法获取路径 Swift Playground 错误的沙箱扩展

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

最佳答案

需要导入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()

关于json - 无法获取路径 Swift Playground 错误的沙箱扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46879277/

相关文章:

c - 程序收到信号 : “EXC_BAD_ACCESS” ?

JavaScript pCloud API 调用获取用户信息出现错误

javascript - 如何使用 stringify 函数将具有 html 对象的 JSON 中的字符串转换?

ios - 如何在 Swift 项目中编译 MagicalRecord?

ios - 使用 Swift 的选项卡式 iOS WebKit 浏览器

iphone - 为什么我会看到有关 NSAutoreleasePool 不可用的警告消息?

ios - 如何在不连接 socket 的情况下将 Storyboard的按钮颜色设置为常用颜色

java - 如何在没有点击的情况下从 recyclerview 适配器中删除所需的项目?或来自列表

java - 使用 Iterator 解析 JSON 并相应地在 listview 中设置它

swift - 使用 Alamofire 发布并解析响应 | swift 5