【问题标题】:The file “XXX” doesn’t exist文件“XXX”不存在
【发布时间】:2017-02-26 09:27:44
【问题描述】:

我正在尝试使用前台互联网操作下载文件。下载成功但问题是目录中不存在文件

代码:

   let urlString = "https://joycemusic1.files.wordpress.com/2015/07/fight-song-rachel_platten.pdf"
        let filePath = "Documents/"

        if let url = NSURL(string: urlString){

            let tast = NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: { (NSURL, NSURLResponse, NSError) in
                if let error = NSError{
                    print(error)
                }
                if let locationString = NSURL , let fileLocation = locationString.path {

                    //print(fileLocation)

                    let fileExists = NSFileManager().fileExistsAtPath("fight-song-rachel_platten.pdf")

                    if fileExists == true{
                       try! NSFileManager.defaultManager().moveItemAtPath(fileLocation, toPath: filePath)
                    }
                }
            })
            tast.resume()
        }

下载文件路径为:

/Users/twilight/Library/Developer/CoreSimulator/Devices/80CCC33B-817F-46C7-A65E-2B1CAA86D940/data/Containers/Data/Application/43CB754B-4096-47B1-9A97-32D1657E426B/tmp/CFNetworkDownload_EoIzdN.tmp

找不到文件

【问题讨论】:

  • NSFileManager().fileExistsAtPath("fight-song-rachel_platten.pdf")。那是一条什么样的路?
  • @vadian 感谢您的指导,您能帮忙解决这个问题吗

标签: ios swift xcode nsfilemanager


【解决方案1】:

对于 Swift 4.0 |使用下面的代码:

  • 您必须检查文件是否存在于 fileLocation

    let fileExists : Bool = FileManager.default.fileExists(atPath: fileLocation)
    
  • 文件路径 Documents/ 根本不存在。您必须使用

    获取沙箱中文档文件夹的 URL
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    
    let dataPath = documentsDirectory.appendingPathComponent(fileLocation)
    

【讨论】:

    【解决方案2】:

    有两个主要错误。

    • 您必须检查文件是否存在于fileLocation

      let fileExists = NSFileManager().fileExistsAtPath(fileLocation)
      
    • 文件路径Documents/ 根本不存在。您必须使用

      获取沙盒中文档文件夹的 URL
      let documentsURL = try! FileManager.default.url(for: .documentDirectory, 
                                                       in: .userDomainMask, 
                                           appropriateFor: nil, 
                                                   create: false)
      

      (抱歉,这是 Swift 3 代码)

    • 与错误无关,但在打印错误后写入return以退出完成块。

    永远不要使用类名NSURLNSURLResponseNSError作为变量名,改用urlresponseerror

    【讨论】:

    • 我正在使用 swift 2 。错误一行上的连续语句必须用';'分隔
    • 我知道,这就是我写抱歉,这是 Swift 3 代码的原因。你需要把它翻译回 Swift 2 或者——最好是——将你的项目更新到 Swift 3
    • 我找不到任何东西我怎么能回到 Swift 2 我也检查了这个 stackoverflow.com/questions/37828700/… 。你能给我一些提示吗
    • 最简单的方法是重新键入以NSFileManager.defaultManager().url开头的方法并使用代码完成(有两种方法urlForurlsFor。你需要第一个)。但最好的方式是将项目更新到 Swift 3。这就是未来。
    • 不,继续学习 Swift。 PS:但是尝试真正学习它,而不是仅仅复制和粘贴代码而不知道它的作用。
    猜你喜欢
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2022-12-10
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    相关资源
    最近更新 更多