简体   繁体   English

本地文件路径不会导入

[英]local file path won't import

I am trying to import the content of a .txt file to a string in my Xcode 9 project using Swift 4. When I use the full path name it imports successfully, current code: 我正在尝试使用Swift 4将.txt文件的内容导入到Xcode 9项目中的字符串中。当我使用完整路径名成功导入当前代码时:

let filePath = URL(fileURLWithPath: "/Users/main/Documents/ClaasPDI/PDIapp/PDIapp/holdMachines.txt")

do
{
    machineString = try String(contentsOf: filePath)

}
catch
{
    print("MACHINE INFORMATION DID NOT IMPORT")
}

I want to be able to import the data from the local path so it can be run on other computers besides mine. 我希望能够从本地路径导入数据,以便可以在我的计算机以外的其他计算机上运行该数据。 My swift files and holdMachines.txt are in the same folder PDIapp but when I change the code to: 我的快捷文件和holdMachines.txt位于同一文件夹PDIapp中,但是当我将代码更改为:

let filePath = URL(fileURLWithPath: "holdMachines.txt")

it now crashes my app and says it could not access the file. 现在它使我的应用程序崩溃,并说它无法访问该文件。

I also tried it with a / infront of the file name (below) but that also failed. 我还在文件名的/前面尝试了它(如下),但这也失败了。

let filePath = URL(fileURLWithPath: "/holdMachines.txt")

How can I change my code to access the file through a local file path? 如何更改代码以通过本地文件路径访问文件?

Put the text file in your Xcode project and use the following code to read it into a string: 将文本文件放入Xcode项目中,并使用以下代码将其读取为字符串:

let txtFile = Bundle.main.path(forResource: "holdMachines", ofType: "txt")
do {
        let contents = try? String(contentsOfFile: txtFile!, encoding: .utf8)
} catch let err {
        print(err.localizedDescription)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM