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/

相关文章:

ios - 是在 AppDelegate 中的 didFinishLaunchingWithOptions 之前初始化 Controller 加载

iphone - 删除了Team Provisioning Profile :* in the Provisioning Portal,怎么办?

ios - 如何在react-native中重置ios库?

swift - 在 Swift 中使用 selectedIndexSet 从 Cocoa NSOutlineView 获取多个项目

c# - C# 中的 Google Geocoding Json 解析问题

javascript - <optgroup> 在 $.each 循环上使用 JSON

ruby - 将 JSON 字符串 append 到 Ruby 中已包含 JSON 的文件

ios - 读取包含子集合的文档的 Firestore 计费

iphone - 将 2D NSMutableArray 转换为 JSON 格式 - JSONKit

iOS 应用程序崩溃,因为 -[UIView _setLayerConfig :]: unrecognized selector sent to instance