我使用此代码将文件保存在文档目录
中func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL){
let fileName = downloadTask.originalRequest?.url?.lastPathComponent
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath:String = path[0]
let fileManager = FileManager()
let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/\(String(describing: fileName!))"))
do {
try fileManager.moveItem(at: location, to: destinationURLForFile)
}catch{
print("error")
}
该文件保存此路径/Documents/filename
但我想保存这样的文件:/Documents/Folder/filename
怎么做?
答案 0 :(得分:3)
在将文件移动到该目录之前,您需要先create directory,如下所示:
let fileName = downloadTask.originalRequest?.url?.lastPathComponent
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath:String = path[0]
let fileManager = FileManager()
var destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appending("/Folder")) //\(String(describing: fileName!))
do {
try fileManager.createDirectory(at: destinationURLForFile, withIntermediateDirectories: true, attributes: nil)
destinationURLForFile.appendPathComponent(String(describing: fileName!))
try fileManager.moveItem(at: location, to: destinationURLForFile)
}catch(let error){
print(error)
}
答案 1 :(得分:2)
像这样创建目录 -
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.appendingPathComponent("MyFolder")!
do {
try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
答案 2 :(得分:0)
试试此代码
let fileManager = NSFileManager.defaultManager()
// Move '/Documents/filename.hello.swift' to '/Documents/Folder/filename/hello.swift'
do {
try fileManager.moveItemAtPath("hello.swift", toPath:
"/Documents/Folder/filename/hello.swift")
}
catch let error as NSError {
print("it did not worked\(error)")
}
希望有所帮助