读取存储在Xcode项目中的文件

时间:2023-01-13 20:14:32

this is a little hard to explain, I want to be able to read from some files which I have on my computer in an iOS app. I am storing the files in the same directory as my 'ViewController.swift' file.

这有点难以解释,我希望能够从iOS应用程序中的计算机上读取一些文件。我将文件存储在与'ViewController.swift'文件相同的目录中。

读取存储在Xcode项目中的文件

My question is, if I want to read from the file "testData.csv", how should I go about referencing it in my app?

我的问题是,如果我想从文件“testData.csv”中读取,我该如何在我的应用程序中引用它?

3 个解决方案

#1


3  

Try this:

let file = NSBundle.mainBundle().pathForResource("testData", ofType: "cvs")
var contents = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!

#2


2  

let bundlePath = NSBundle.mainBundle().pathForResource("testdata", ofType: "csv")
var textContent = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
println(textContent)

To make the code generic and reusable, You can define a function which accepts your file name as well file type.

为了使代码具有通用性和可重用性,您可以定义一个接受文件名和文件类型的函数。

Happy coding.

#3


1  

Get file URL

获取文件URL

let fileUrl = NSBundle.mainBundle().URLForResource("testData", withExtension: "csv")

Then you can parse the file using this swift lib https://github.com/naoty/SwiftCSV

然后你可以使用这个swift lib https://github.com/naoty/SwiftCSV来解析文件

#1


3  

Try this:

let file = NSBundle.mainBundle().pathForResource("testData", ofType: "cvs")
var contents = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!

#2


2  

let bundlePath = NSBundle.mainBundle().pathForResource("testdata", ofType: "csv")
var textContent = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
println(textContent)

To make the code generic and reusable, You can define a function which accepts your file name as well file type.

为了使代码具有通用性和可重用性,您可以定义一个接受文件名和文件类型的函数。

Happy coding.

#3


1  

Get file URL

获取文件URL

let fileUrl = NSBundle.mainBundle().URLForResource("testData", withExtension: "csv")

Then you can parse the file using this swift lib https://github.com/naoty/SwiftCSV

然后你可以使用这个swift lib https://github.com/naoty/SwiftCSV来解析文件