【问题标题】:To check file Existence at filepath (Handling exception) in Swift 3在 Swift 3 中检查文件路径中的文件存在(处理异常)
【发布时间】:2017-03-02 05:58:51
【问题描述】:

我正在尝试检查 swift 3 中的路径中是否存在文件,但它总是显示“NO FILE EXIST”

我也试过 atPath: self.strTitle+"/back/index.html" 甚至这也行不通。

这里的 strTitle 是位于资产文件夹内的文件路径,并通过数组读取。有两页,一页在背面,一页在正面。因此,所有内容都有正面,但背面页面仅限于少数。这就是它崩溃的地方。

print("STR TITLE::  ",self.strTitle) .   // STR TITLE = assets/a6th_nerve_palsy
let fileManager : FileManager   = FileManager.default

if fileManager.fileExists(atPath: self.strTitle+"/back/index"){
    print("FILE EXIST")

    }else{
        print("NO FILE EXIST")
    }

提前致谢:)

【问题讨论】:

  • 你是从你的包中获取文件吗?
  • 是的。我已将其全部存储在我的资产中
  • 如果文件明显存在,你为什么要检查你把自己放在你的资产中的文件?只需使用 Bundle.main.url(forResource: "fileName", withExtension: "ext") 获取您的资源 url 如果您的文件位于子目录中,请使用 Bundle.main.url(forResource: "fileName", withExtension: "ext", subdirectory: "subdirectory") stackoverflow.com/questions/34548771/…
  • 谢谢@LeoDabus 我在你的链接帮助下找到了解决方法。将在这里发布我的答案:)
  • 试试bundle.path(forResource: "index", withExtension: "html", subdirectory: strTitle + "/back" )

标签: uiwebview swift3 nsfilemanager file-exists


【解决方案1】:

要找到路径,您应该尝试此代码。

class Controller : UIViewController {

    override func viewDidLoad() {
        let bundle = Bundle(for: Controller.self)
        let filePath = bundle.path(forResource: "index", ofType: "html")
        let fileManager : FileManager   = FileManager.default

        if fileManager.fileExists(atPath: filePath!){
            print("file found")
        } else {
            print("file not found")
        }
    }

}

【讨论】:

  • 如果 fileManager.fileExists(atPath: filePath!) 它此时会中断
  • 在展开可选值时意外发现 nil
  • 你能在建议后发布你身边的最新代码吗
【解决方案2】:

经过调试并在@LeoDabus 的帮助下,我可以弄清楚。可以直接检查文件路径是否存在。

let bundle = Bundle(for: PageContentViewController.self)
let filePath = bundle.path(forResource: self.strTitle+"/back/index", ofType: "html")

        if filePath == nil{
            print("FILE NOT FOUND")
            // Show No page as page do not exist
        } else {
            print("FILE FOUND")
            // Show Back page
        }

谢谢大家。 :)

【讨论】:

    【解决方案3】:
    let fileName = getDocumentsDirectory().appendingPathComponent("\(lastPath)")
              if FileManager.default.fileExists(atPath: fileName){
                            try? FileManager.default.removeItem(atPath: fileName)
                   }
    
    func getDocumentsDirectory() -> NSString {
         let paths =  NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0]
        return documentsDirectory as NSString
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      相关资源
      最近更新 更多