user8486780
user8486780

Reputation:

swift: save file document directory

I use this code to save file in document directory

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")
        }

And the file saves for this path /Documents/filename

But I want to save the file like this: /Documents/Folder/filename

How to do it?

Upvotes: 4

Views: 9232

Answers (3)

Puneet Sharma
Puneet Sharma

Reputation: 9484

You would need to create directory first before moving the file to that directory, something like this:

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)
}

Upvotes: 5

Abhishek Jain
Abhishek Jain

Reputation: 4739

Create Directory like this -

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);
}

Upvotes: 2

cole
cole

Reputation: 3347

Try this code

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)")
  }

Hope it helps

Upvotes: 0

Related Questions