Xcode 7 Playgrounds现在支持从嵌套的Resources目录加载文件。

如果我的SKScene(fileNamed: "GameScene")中有一个GameScene.sks,或者如果你的Resources中有NSImage(named:"GameScene.png"),则我可以得到GameScene.png

但是,如何从Playground Resources目录中读取常规文本文件呢?

最佳答案

我们可以使用Bundle.main
因此,如果您在操场上有一个test.json,例如

您可以访问它并打印其内容,如下所示:

// get the file path for the file "test.json" in the playground bundle
let filePath = Bundle.main.path(forResource:"test", ofType: "json")

// get the contentData
let contentData = FileManager.default.contents(atPath: filePath!)

// get the string
let content = String(data:contentData!, encoding:String.Encoding.utf8)

// print
print("filepath: \(filePath!)")

if let c = content {
    print("content: \n\(c)")
}

会列印
filepath: /var/folders/dm/zg6yp6yj7f58khhtmt8ttfq00000gn/T/com.apple.dt.Xcode.pg/applications/Json-7800-6.app/Contents/Resources/test.json
content:
{
    "name":"jc",
    "company": {
        "name": "Netscape",
        "city": "Mountain View"
    }
}

关于ios - 如何使用Swift 2和Xcode 7阅读Playground文本资源文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30957471/

10-14 20:09