簡體   English   中英

讀取本地文本文件內容 get Nil in swift

[英]read local text file content get Nil in swift

我想從 swift 中的一個文本文件中讀取內容,我所做的步驟是

  1. go 到終端並讀取/創建文件
  2. go 到 Xcode,文件 -> 添加文件到我的項目和 select 將 test_this 文件添加到項目中
  3. 使用以下代碼讀取內容。
/// 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項目中。

  1. 打開Xcode並導航到您的項目,確保左側面板顯示項目的文件夾/文件。
  2. 打開Finder並導航到您的test.txt文件。
  3. 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM