gpt4 book ai didi

ios - 读取文件内容无法使用 FileManager

转载 作者:行者123 更新时间:2023-11-30 10:44:36 27 4
gpt4 key购买 nike

我是 Swift 新手。

我正在尝试编写一个简单的应用程序,该应用程序仅读取文件并将其内容转换为字符串。我正在使用 FileManager 和此处给出的 Swift 4 示例:Read and write a String from text file

但是它不起作用。我假设问题是我向 String(contentsOf: URL) 方法提供了错误的 URL。抛出的确切错误是它无法打开该文件,因为它不存在。

下面是我的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
}

其余应用程序文件是通用单 View 应用程序文件。我会包含侧边栏的图像,但当我尝试上传它时,问题编辑器抛出错误。基本上,它看起来像:

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 应用程序的成员。

我不确定我错过了什么。如果这里其他地方回答了这个问题,请指出我的方向,我会结束这个问题。

最佳答案

如果文件位于应用程序 bundle 中,则必须使用 Bundle 的 API

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()

关于ios - 读取文件内容无法使用 FileManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56018358/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com