Jer*_*one 13 xcode ios swift-playground xcode7
XCode 7 Playground支持游乐场资源.如果我的资源中有GameScene.png,那么当我在我的资源或NSImage(名为:"GameScene.png")中有GameScene.sks时,我可以获得SKScene(fileNamed:"GameScene").
但是如何从Playground资源中读取文本文件?
Jer*_*one 30
我们可以使用 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)")
}
Run Code Online (Sandbox Code Playgroud)
会打印
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"
}
}
Run Code Online (Sandbox Code Playgroud)
lea*_*nne 11
Jeremy Chone的答案,更新为Swift 3,Xcode 8:
// 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: .utf8)
// print
print("filepath: \(filePath!)")
if let c = content {
print("content: \n\(c)")
}
Run Code Online (Sandbox Code Playgroud)
您可以直接使用String和URL.Swift 3中的示例:
let url = Bundle.main.url(forResource: "test", withExtension: "json")!
let text = String(contentsOf: url)
Run Code Online (Sandbox Code Playgroud)
雨燕5
可以Resources通过 Playground 中的捆绑包获取文件夹中的文件。
import UIKit
Run Code Online (Sandbox Code Playgroud)
这里有两种获取 JSON 数据的方法。
小路:
guard let path = Bundle.main.path(forResource:"test", ofType: "json"),
let data = FileManager.default.contents(atPath: path) else {
fatalError("Can not get json data")
}
Run Code Online (Sandbox Code Playgroud)
网址:
guard let url = Bundle.main.url(forResource:"test", withExtension: "json") else {
fatalError("Can not get json file")
}
if let data = try? Data(contentsOf: url) {
// do something with data
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12224 次 |
| 最近记录: |