读取文件内容无法与FileManager一起使用 [英] Reading Contents of File Not Working with FileManager
问题描述
我是Swift的新手.
I am new to Swift.
我正在尝试编写一个简单的应用程序,该应用程序仅读取文件并将其内容转换为字符串.我正在使用FileManager和此处为Swift 4给出的示例:读取和写入文本文件中的字符串
I am trying to write a simple app that just reads a file and converts its contents to a string. I am using FileManager and the example given here for Swift 4: Read and write a String from text file
虽然没有用.我假设的问题是,我给 String(contentsOf:URL)
方法提供了错误的URL.抛出的确切错误是因为它不存在而无法打开文件.
It's not working though. The issue, I am assuming, is that I am giving the wrong URL to the String(contentsOf: URL)
method. The exact error thrown is that it couldn't open the file because it doesn't exist.
下面是我的 ViewController.swift
代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var testText: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let test = directoryContents()
do {
let text = try String(contentsOf: test)
testText.text! = text
}
catch{
print(error.localizedDescription)
}
}
}
func directoryContents() -> URL {
var dirContents: URL!
dirContents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
dirContents = dirContents.appendingPathComponent("testdata.txt")
return dirContents
}
其余的应用程序文件是通用的Single View App文件.我会包含侧边栏的图像,但是当我尝试上传时,问题编辑器抛出了错误.基本上看起来像这样:
The rest of the app files are generic Single View App files. I would include an image of the sidebar, but the question editor was throwing an error when I tried to upload it. Basically, it looks like:
testingData/
testingData/
TestData/
testdata.txt
AppDelegate.swift
ViewController.swfit
Main.storyboard
Assets.xcassets
LaunchScreen.storyboard
Info.plist
Products/
testingData.app
在 Main.storyboard
中添加了 TextView
,它是我的 ViewController
中的 testText
.我试图读取的文件是 testdata.txt
,这是一个文本文件,其中包含文本 1,2,3,4,5,6
.它是 testingData
应用程序的成员.
The Main.storyboard
has a TextView
added to it that is the testText
in my ViewController
. The file I am trying to read in is the testdata.txt
, which is a text file containing the text 1,2,3,4,5,6
and nothing else. It is a member of the testingData
app.
我不确定我缺少什么.如果在这里的其他地方回答了这个问题,请指出我的方向,然后我将其解决.
I'm not sure what I'm missing. If this is answered somewhere else on here, kindly point me in that direction and I'll close this out.
推荐答案
如果该文件位于应用程序捆绑包中,则必须使用 Bundle
If the file is in the application bundle you have to use the API of Bundle
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let test = Bundle.main.url(forResource:"testdata", withExtension: "txt")!
do {
let text = try String(contentsOf: test)
testText.text! = text
}
catch {
print(error)
}
}
并删除 directoryContents()
这篇关于读取文件内容无法与FileManager一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!