【问题标题】:Move item after downloaded [duplicate]下载后移动项目[重复]
【发布时间】:2017-11-26 14:57:45
【问题描述】:

我目前正在下载文件。下载完成后我想将下载的文件移动到apps文档目录,我的设置:

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    debugPrint("didFinishDownloadingTo: \(location)")

    let documentsDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let saveDirectory = documentsDirectory.appendingPathComponent("file1.mp4")

    do {
        try FileManager.default.moveItem(at: location, to: saveDirectory)
    } catch {
        print("didFinishDownloadingTo error \(error.localizedDescription)")
    }
}

有时我想查看所有下载的文件:

do {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = String(describing: paths[0])

    let items = try FileManager.default.contentsOfDirectory(atPath: documentsDirectory)

    for item in items {
        print("Found \(item)")
    }
} catch {
    print("contentsOfDirectory \(error.localizedDescription)")
}

这部分抛出:

The folder “Documents” doesn’t exist.

didFinishDownloadingTo 方法没有抛出错误,所以我假设 moveitem 函数成功了,但我不知道为什么我不能列出我的项目... 我做了一些研究,但没有结果,我不知道为什么我不能列出。

【问题讨论】:

  • 不要使用String(describing:) 方法。它将返回您的 url absoluteString,其中包括“file://”前缀(url 方案)。只需使用您的文档目录 url 路径属性。 FileManager.default.contentsOfDirectory(atPath: paths.first!.path)

标签: ios swift asynchronous download document


【解决方案1】:

通过简单地打印路径并检查这些文件夹来尝试调试。这样您就可以看到哪个步骤没有按预期工作。我认为路径有一个小错误,在调试时可能更容易发现。

提示:使用模拟器而不是真实设备进行调试。因为它会使浏览文件夹变得更加容易。

希望对你有帮助。

【讨论】:

  • OP 问题是使用包含 url 方案的 url absoluteString。
  • 什么是OP? @LeoDabus
  • 原创海报(创意密码器):)
  • 明白了。谢谢:) @LeoDabus
  • @LeoDabus 请问您为什么更喜欢在 cmets 中而不是在答案部分中回答,以便人们看到解决方案?
猜你喜欢
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
  • 2020-08-02
  • 1970-01-01
  • 2020-03-31
  • 2021-09-04
  • 1970-01-01
相关资源
最近更新 更多