当前位置:  开发笔记 > 编程语言 > 正文

为什么Bundle.main.path(forResource:fileName,ofType:"txt")总是返回nil?

如何解决《为什么Bundle.main.path(forResource:fileName,ofType:"txt")总是返回nil?》经验,为你挑选了1个好方法。

我想逐行阅读文本文件,并使用此处显示的示例在iOS屏幕上显示它.

制作textView.text可选项是我能够readDataFromFile运行的唯一方式.当我单击load该函数运行但总是返回nil.我认为这意味着找不到文件.

出于测试目的,我在Xcode中创建了文本文件.我也尝试将它保存在桌面和项目文件夹中.无论哪种方式,它都可以从项目导航器中读取.我还尝试使用TextEdit创建文件,因为应用程序最终需要读取在Xcode外部创建的文本文件.

如果有人可以解释为什么永远不会找到文本文件,我是否感激不已,为了让项目找到它还是需要做些什么,或者nil由于我的方式而导致读取函数由于其他原因而返回实施了它.谢谢.

编辑(2)

感谢您的反馈.作为回应,我做了四个小的代码更改,允许将文本文件内容写入textView.更改包括:从文件名中删除文件扩展名,添加文件名数组,String而不是String?从代码中返回readDataFromFile和重写UITextView.这解决了我所知道的问题.

这是修改后的代码

import UIKit

class ViewController: UIViewController {

var textView = UITextView()
var arrayOfStrings: [String]?
var fileNameWithExtension               = "textFile.txt"
let arrayOfFileNames                    = ["textFile1.txt", "textFile2.txt", "textFile3.txt", "textFile4.txt", "textFile5.txt"]

var fileName                            = String()

override func viewDidLoad() {
    super.viewDidLoad()

    //    remove comment in the next statement to test files named in ArrayOfFileNames    
    //    fileNameWithExtension               = arrayOfFileNames[4]

    fileName = fileNameWithExtension.replacingOccurrences(of: ".txt", with: "")

    createTextView()
    createButton()
}

func readDataFromFile(fileName: String) -> String {

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

        print(fileName)

        do {
            let data                    = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
            arrayOfStrings              = data.components(separatedBy: .newlines)
            textView.text               = arrayOfStrings?.joined(separator: "\n")

        } catch {
            textView.text               = "file contents could not be loaded"
        }

    } else {
        print(Bundle.main.path(forResource: fileName, ofType: "txt") as Any)
        textView.text                   = "\(fileName) could not be found"
    }
    return textView.text
}

func createButton () {
    let button = UIButton();
    button.setTitle(String("Load"), for: .normal)
    button.setTitleColor(UIColor.blue, for: .normal)
    button.frame = CGRect(x: 100, y: 10, width: 200, height: 100)
    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    self.view.addSubview(button)
}

func buttonAction(myButton: UIButton) {
    textView.text = readDataFromFile(fileName: fileName)
    print(textView.text as Any)
}

func createTextView () {
    textView = UITextView(frame: CGRect(x: 20.0, y: 75.0, width: 340.0, height: 400.0))
    textView.textAlignment = NSTextAlignment.left
    textView.textColor = UIColor.blue
    textView.backgroundColor = UIColor.white
    self.view.addSubview(textView)
    }
}

编辑(1)

该文件在项目导航器中可见.我会假设这意味着它在捆绑中.

这是我的原始代码

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var textView: UITextView?

var arrayOfStrings: [String]?
var fileName                            = "textFile.txt"

override func viewDidLoad() {
    super.viewDidLoad()
    createButton()
}

func readDataFromFile(fileName: String) -> String? {

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

        do {
            let data                    = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
            arrayOfStrings              = data.components(separatedBy: .newlines)
            print(arrayOfStrings as Any)

            textView?.text              = arrayOfStrings?.joined(separator: "/n")
            return textView?.text

        } catch {
            textView?.text              = "file contents could not be loaded"
            return textView?.text
        }

    } else {
        print(Bundle.main.path(forResource: fileName, ofType: "txt") as Any)
        textView?.text                  = "\(fileName) could not be found"
        return nil
    }
}

func createButton () {
    let button = UIButton();
    button.setTitle(String("Load"), for: .normal)
    button.setTitleColor(UIColor.blue, for: .normal)
    button.frame = CGRect(x: 100, y: 15, width: 200, height: 100)
    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    self.view.addSubview(button)
}


func buttonAction(myButton: UIButton) {
    print("works")
    textView?.text                      = readDataFromFile(fileName: fileName)
    print(textView?.text as Any)
}

TextFile.txt的

Line 1
Line 2
Line 3
Line 4
Line 5

Igor.. 7

1)你在这一行有错误:

var fileName = "textFile.txt"

应该:

var fileName = "textFile"

2)检查是您连接到目标的文件:

在此输入图像描述



1> Igor..:

1)你在这一行有错误:

var fileName = "textFile.txt"

应该:

var fileName = "textFile"

2)检查是您连接到目标的文件:

在此输入图像描述

推荐阅读
放ch养奶牛
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有