【问题标题】:Get file path from NSBundle in Swift在 Swift 中从 NSBundle 获取文件路径
【发布时间】:2015-12-17 14:59:23
【问题描述】:

我有一个文件存储在:

/var/mobile/Containers/Data/Application/083EA15E7/Documents/myFile.zip

它是在我从服务器下载后到达那里的。

如果我知道文件名为myFile.zip,如何使用NSBundle 找到它?

像这样:

if let URL = NSBundle.mainBundle().URLForResource("myFile", withExtension: "zip") {
    // do stuff
}

目前返回 false,不确定如何指定整个路径。有什么想法吗?

【问题讨论】:

    标签: swift file nsbundle


    【解决方案1】:

    此项目不在您的捆绑包中,捆绑包中的项目是您在编译之前添加的内容,例如资产、字体等。

    iOS 为每个应用程序提供了一个沙盒。在该沙箱中,存在 Documents 文件夹。要访问 Documents 文件夹中的文件,请尝试以下操作:

    let documentsURL = NSURL(
      fileURLWithPath: NSSearchPathForDirectoriesInDomains(
        .DocumentDirectory, .UserDomainMask, true).first!,
      isDirectory: true
    )
    

    要获取文件,您需要获取其路径并将其附加到文档路径,如下所示。

    let URLToMyFile = documentsURL.URLByAppendingPathComponent("MyFile.zip")
    

    要以字符串形式获取路径,您可以访问 URL 的路径属性。

    print(URLToMyPath.path!)
    

    这将打印出你下载资源的路径。

    【讨论】:

    • 目标 c 等价??请问??
    【解决方案2】:

    测试于:xCode 8.3.2Swift 3.1

    首先将文件(JPG、MP3、ZIP)拖到项目文件夹中,并确保选中Copy items if needed并在添加到目标中选择项目/应用>

    里面相关的ViewController

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

    如果你需要获取文件的 URL 可以使用 NSBundle 方法

    if let fileURL = Bundle.main.url(forResource: fileName, withExtension: fileType) {
        print(fileURL)
    }
    

    NSBundle 方法 pathForResource 也有一个初始化器,您可以指定文件所在的目录,例如:

    if let filePath = Bundle.main.path(forResource: fileName, ofType: fileType, inDirectory: "filesSubDirectory") {
        print(filePath)
    }
    

    以及获取文件 URL:

    if let fileURL = Bundle.main.url(forResource: fileName, withExtension: fileType, subdirectory: "filesSubDirectory") {
        print(fileURL)
    }
    

    【讨论】:

      【解决方案3】:

      运行时创建的文件存储在文档目录而不是 NSBundle 中。 NSBundle 存储您在开发时放入 Xcode 项目中的系统文件之类的文件

      这是一个例子

      此代码在 Swift 2.0 上经过全面测试

      let file = "myFile.zip"
              if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
                 //path will be stored here
                  let sPath = dir.stringByAppendingPathComponent(file);
      
            print(sPath) //  printing the file path
      
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-15
        • 2011-11-16
        • 2012-01-21
        相关资源
        最近更新 更多