0

我需要在我的 iphone 中使用 swift 读取文件。在我的计算机中,我使用此代码并正常运行。文件“test.txt”在我的桌面中。

import UIKit

class Controller: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let sourcePath = URL(fileURLWithPath: "/Users/myname/Desktop", isDirectory: true)
        let file : URL = URL(fileURLWithPath: "test.txt", relativeTo: sourcePath)

        let filemgr = FileManager.default

        if filemgr.fileExists(atPath: file.path){
            do{
                //Code to Parse text
            } catch let error as NSError{
            print ("Error: \(error)")
            }
        }
    }
}

问题是我需要在我的 iphone 中读取这个文件。但我不知道哪个是读取文件的 URL。我可以在哪里保存文件,哪个是 URL?

谢谢

4

2 回答 2

0

1-将文本文件拖到项目中并选择copy Items If needed

2-用这个来阅读它

do {

    if let path  = Bundle.main.path(forResource: "fileName", ofType: "txt") {

        let str = try String(contentsOfFile:path, encoding: .utf8)

        print(str)
    }


}

catch  {

    print(error)
}
于 2018-07-19T09:17:21.733 回答
0

这个问题的简单答案是您无法将文件从桌面读取到您的设备。该文件应该在您的应用程序文档目录中,或者您需要将该文件添加到您的项目中。

之后,您可以将其读入设备。

于 2018-07-19T09:12:32.523 回答