【发布时间】: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:)方法。它将返回您的 urlabsoluteString,其中包括“file://”前缀(url 方案)。只需使用您的文档目录 url 路径属性。FileManager.default.contentsOfDirectory(atPath: paths.first!.path)
标签: ios swift asynchronous download document