Подтвердить что ты не робот

Как читать файлы текстовых ресурсов игровой площадки с помощью Swift 2 и Xcode 7

Игровые площадки Xcode 7 теперь поддерживают загрузку файлов из вложенного каталога Resources.

Я могу получить SKScene(fileNamed: "GameScene") когда у меня есть GameScene.sks в моих Resources или NSImage(named:"GameScene.png") если у меня есть GameScene.png в ваших Resources.

Но как я могу прочитать обычный текстовый файл из каталога Playground Resources?

4b9b3361

Ответ 1

Мы можем использовать Bundle.main

Итак, если у вас есть test.json на вашей игровой площадке, например

enter image description here

Вы можете получить к нему доступ и распечатать его содержимое следующим образом:

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

Ответ 2

Ответ Джереми Чоне, обновленный для 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)")
}

Ответ 3

Вы можете напрямую использовать String с URL-адресом. Пример в Swift 3:

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

Ответ 4

Еще один короткий путь (Swift 3):

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

Ответ 5

Добавлена ​​попытка для 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
}

Ответ 6

Swift 5

Получить файлы в папке Resources можно с помощью набора на игровой площадке.

import UIKit

Вот два способа получить данные 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")
    }

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
    }