【问题标题】:Can`t copy file from bundle to documents directory in iOS无法将文件从捆绑包复制到 iOS 中的文档目录
【发布时间】:2016-03-24 14:35:30
【问题描述】:

我正在尝试使用以下代码将文件从我的包复制到 iOS 中的文档目录。

let bundlePath = NSBundle.mainBundle().pathForResource("information", ofType: ".png")
print(bundlePath, "\n") //prints the correct path
let destPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
let fileManager = NSFileManager.defaultManager()
let fullDestPath = NSURL(fileURLWithPath: destPath).URLByAppendingPathComponent("information.png")
let fullDestPathString = String(fullDestPath)
print(fileManager.fileExistsAtPath(bundlePath!)) // prints true

do{
try fileManager.copyItemAtPath(bundlePath!, toPath: fullDestPathString)
}catch{
    print("\n")
    print(error)
}

Error Domain=NSCocoaErrorDomain Code=4 "文件“information.png”不存在。" UserInfo={NSSourceFilePathErrorKey=/Users/macbookpro/Library/Developer/CoreSimulator/Devices/E58CA1C6-C6F1-4D72-9572-3925675E78A5/data/Containers/Bundle/Application/EFA83E02-5F24-4BB3-B32A-7E755081A730/AutoLayout tuts.app /information.png, NSUserStringVariant=( 复制 ), NSDestinationFilePath=file:///Users/macbookpro/Library/Developer/CoreSimulator/Devices/E58CA1C6-C6F1-4D72-9572-3925675E78A5/data/Containers/Data/Application/86A1BDD5-FAF2-486E-85A9-CF72A547C6CD/Documents /information.png, NSFilePath=/Users/macbookpro/Library/Developer/CoreSimulator/Devices/E58CA1C6-C6F1-4D72-9572-3925675E78A5/data/Containers/Bundle/Application/EFA83E02-5F24-4BB3-B32A-7E755081A730/AutoLayout tuts .app/information.png, NSUnderlyingError=0x7fb53251cd80 {Error Domain=NSPOSIXErrorDomain Code=2 "没有这样的文件或目录"}}

根据fileManager.fileExistsAtPath(),该文件确实存在。我做错了什么?

【问题讨论】:

    标签: ios swift copy bundle


    【解决方案1】:

    问题出在这一行:

    let fullDestPathString = String(fullDestPath)
    

    应该是:

    let fullDestPathString = fullDestPath.path
    

    查看错误。问题是目的地。注意file:///。您的代码未正确将 URL 转换为文件路径。您需要使用NSURLpath 属性以字符串形式获取路径。

    在您所有的调试和检查中,您从未验证过fullDestPathString 的值。

    【讨论】:

    • 谢谢,现在可以使用了。我什至没有想过要查看fullDestPathString,因为错误消息:“文件信息.png 不存在”。这就是为什么我完全专注于那个。
    • 同样的问题,仍然有问题
    • @TheBaj 同意,错误信息令人沮丧地误导!
    【解决方案2】:

    要获得你应该使用的字符串路径

    let path = fullDestPath.path
    

    附注

    fileManager.fileExistsAtPath(bundlePath!) == true 
    

    是检查值是否为真的方法

    fileManager.fileExistsAtPath(bundlePath!)
    

    这可能会有一些问题

    【讨论】:

      【解决方案3】:

      请在下面找到代码。我参考了@rmaddy 的回答。

      func CheckDataBaseOnPathorNot() -> Void {
              let bundlePath = Bundle.main.path(forResource: "Project_Expert", ofType: ".db")
              print(bundlePath ?? "", "\n") //prints the correct path
              let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
              let fileManager = FileManager.default
              let fullDestPath = NSURL(fileURLWithPath: destPath).appendingPathComponent("Project_Expert.db")
              let fullDestPathString = fullDestPath!.path
              print(fileManager.fileExists(atPath: bundlePath!)) // prints true
              if fileManager.fileExists(atPath: fullDestPathString) {
                  print("File is available")
              }else{
                  do{
                      try fileManager.copyItem(atPath: bundlePath!, toPath: fullDestPathString)
                  }catch{
                      print("\n")
                      print(error)
      
                  }
              }
      
          }
      

      如果文件在路径上不可用,请检查此代码,然后复制文件。

      谢谢。

      【讨论】:

        【解决方案4】:

        斯威夫特 3

        func copyfileToDocs()
            {
                let bundlePath = Bundle.main.path(forResource: "db", ofType: ".sqlite")
                print(bundlePath!, "\n") //prints the correct path
                let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
                let fileManager = FileManager.default
                let fullDestPath = NSURL(fileURLWithPath: destPath).appendingPathComponent("db.sqlite")
                let fullDestPathString = fullDestPath?.path
                print(fileManager.fileExists(atPath: bundlePath!)) // prints true
                do
                {
                    try fileManager.copyItem(atPath: bundlePath!, toPath: fullDestPathString!)
                    print("DB Copied")
                }
                catch
                {
                    print("\n")
                    print(error)
                }
            }
        

        【讨论】:

          【解决方案5】:

          斯威夫特 4

          在某些答案中具有误导性:

          打印(fileManager.fileExists(atPath: bundlePath!))

          因此提出这个extension 版本:

          extension FileManager {
              func copyfileToUserDocumentDirectory(forResource name: String,
                                                   ofType ext: String) throws
              {
                  if let bundlePath = Bundle.main.path(forResource: name, ofType: ext),
                      let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                          .userDomainMask,
                                          true).first {
                      let fileName = "\(name).\(ext)"
                      let fullDestPath = URL(fileURLWithPath: destPath)
                                             .appendingPathComponent(fileName)
                      let fullDestPathString = fullDestPath.path
          
                      if !self.fileExists(atPath: fullDestPathString) {
                          try self.copyItem(atPath: bundlePath, toPath: fullDestPathString)
                      }
                  }
              }
          }
          

          用法

          try fileManager.copyfileToUserDocumentDirectory(forResource: "information",
                                                          ofType: "png")
          ...
          

          【讨论】:

            猜你喜欢
            • 2020-06-02
            • 2011-05-02
            • 2012-04-07
            • 1970-01-01
            • 2016-07-13
            • 2011-09-05
            • 2014-03-27
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多