如何使用 Swift 2 和 Xcode 7 读取游乐场文本资源文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30957471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:20:58  来源:igfitidea点击:

How to read a playground text resource files with Swift 2 and Xcode 7

iosxcodeswift-playgroundxcode7

提问by Jeremy Chone

Xcode 7 Playgrounds now supports loading files from the nestedResourcesdirectory.

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

I can get SKScene(fileNamed: "GameScene")when I have a GameScene.sksin my Resourcesor NSImage(named:"GameScene.png")if I have a GameScene.pngin your Resources.

我可以SKScene(fileNamed: "GameScene")当我有一个GameScene.sks在我的Resources或者NSImage(named:"GameScene.png")如果我有一个GameScene.png在你的Resources

But how can I read a regular text file from the Playground Resourcesdirectory as well?

但是我怎样才能从 PlaygroundResources目录中读取一个普通的文本文件呢?

回答by Jeremy Chone

We can use the Bundle.main

我们可以使用 Bundle.main

So, if you have a test.json in your playground like

所以,如果你在你的操场上有一个 test.json 像

enter image description here

在此处输入图片说明

You can access it and print its content like that:

您可以像这样访问它并打印其内容:

// 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)")
}

Will print

会打印

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"
    }
}

回答by leanne

Jeremy Chone'sanswer, updated for Swift 3, Xcode 8:

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)")
}

回答by Damiaan Dufaux

You can use String directly with a URL. Example in Swift 3:

您可以直接将 String 与 URL 一起使用。Swift 3 中的示例:

let url = Bundle.main.url(forResource: "test", withExtension: "json")!
let text = String(contentsOf: url)

回答by Yoav Aharoni

Another short way (Swift 3):

另一个捷径(Swift 3):

let filePath = Bundle.main.path(forResource: "test", ofType: "json")
let content: String = String(contentsOfFile: filePath!, encoding: .utf8)

回答by user8416808

Added try for swift3.1:

为 swift3.1 添加尝试:

let url = Bundle.main.url(forResource: "test", withExtension: "json")!
// let text = String(contentsOf: url)
do {
    let text = try String(contentsOf: url)
    print("text: \n\(text)")
}
catch _ {
    // Error handling
}

// --------------------------------------------------------------------
let filePath2 = Bundle.main.path(forResource: "test", ofType: "json")
do {
    let content2: String = try String(contentsOfFile: filePath2!, encoding: .utf8)
    print("content2: \n\(content2)")

}
catch _ {
    // Error handling
}

回答by skymook

Swift 5

斯威夫特 5

It is possible to get to files in your Resourcesfolder by the bundle in a Playground.

可以Resources通过 Playground 中的捆绑包访问文件夹中的文件。

import UIKit

Here are two ways to get the JSON data.

这里有两种获取 JSON 数据的方法。

Path:

小路:

    guard let path = Bundle.main.path(forResource:"test", ofType: "json"),
    let data = FileManager.default.contents(atPath: path) else {
        fatalError("Can not get json data")
    }

URL:

网址:

    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
    }