2015-06-20 28 views
10

XCode 7遊樂場支持遊樂場資源。如果我的資源中有GameScene.png,則在我的Resources或NSImage(名爲:「GameScene.png」)中有GameScene.sks時,我可以獲得SKScene(fileNamed:「GameScene」)。如何用Swift 2和XCode 7讀取操場文本資源文件

但是如何從Playground資源讀取文本文件?

回答

22

我們可以使用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" 
    } 
} 
+0

這裏是很好的提。獲得資源的方法是在** WorkSpace **內創建操場。我會默認出現在正確的位置。 – jasmo2

8

Jeremy Chone's答案,更新的斯威夫特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)") 
} 
+0

filePath應該安全使用。請檢查filePath是否爲零,例如使用let。 contentData也應該完成。應該編寫代碼,以便它可以處理這些有問題的情況。 – Heitara

3

您可以通過URL直接使用字符串。例如,在斯威夫特3:

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

另一個短的方式(SWIFT 3):

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

新增嘗試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 
} 
+0

忽略catch塊中的錯誤是非常糟糕的做法。你不應該使用'_'運算符:只需要'catch'並且它會在塊中正確地生成'error'變量。 – Moritz