[英]read local text file content get Nil in swift
我想從 swift 中的一個文本文件中讀取內容,我所做的步驟是
/// terminal
/// $echo "some content" > /Users/test_this
/// swift
let file = "/Users/test_this"
let path = URL(fileURLWithPath: file)
let text = try? String(contentsOf: path)
但是,在打印出文件、路徑和文本之后。 文本為零。 文件和路徑看起來不錯 我如何從 swift 中的文本文件中讀取內容?
假設您已將test.txt
文件添加到您的 Xcode 項目,請嘗試類似這種方法。
struct ContentView: View {
@State var fileTxt = ""
var body: some View {
Text(fileTxt)
.onAppear {
if let theString = readLocalData() {
fileTxt = theString
print("---> fileTxt: \(fileTxt)")
}
}
}
func readLocalData() -> String? {
if let pathString = Bundle.main.path(forResource: "test", ofType: "txt") {
let url = URL(fileURLWithPath: pathString)
do {
return try String(contentsOf: url)
// alternative
// let data = try Data(contentsOf: url)
// return String(data: data, encoding: .utf8)
} catch {
print(error) // <-- here important
}
}
// vadian cleaner alternative
// if let url = Bundle.main.url(forResource: "test", withExtension: "txt") {
// do {
// return try String(contentsOf: url)
// } catch {
// print(error) // <-- here important
// }
// }
return nil
}
}
加上test.txt
文件內容:
Hello World
注意:將文件test.txt
添加到您的Xcode
項目中。
Xcode
並導航到您的項目,確保左側面板顯示項目的文件夾/文件。Finder
並導航到您的test.txt
文件。test.txt
文件從Finder
拖放到您的 Xcode 項目左側面板中。 這樣做之后, Build
然后run
我的代碼。
或者,您可以在 Xcode 中創建一個New File
,方法是:在顯示文件夾/文件的左側面板上單擊鼠標右鍵,然后單擊 select New File...
,向下滾動,然后單擊 select, Empty
文件。 給它起一個名字test.txt
。 該文件將被創建並添加到您的 Xcode 項目中。 在 Xcode 中打開此文件並鍵入: Hello from the test.txt file
。 構建然后運行我的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.