Save file in document directory in swift 3?

82,550

Solution 1

Please think the other way round.

URL is the recommended way to handle file paths because it contains all convenience methods for appending and deleting path components and extensions – rather than String which Apple has removed those methods from.

You are discouraged from concatenating paths like path = path + name. It's error-prone because you are responsible for all slash path separators.

Further you don't need to create a file with FileManager. Data has a method to write data to disk.

let fileManager = FileManager.default
do {
    let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
    let fileURL = documentDirectory.appendingPathComponent(name)
    let image = #imageLiteral(resourceName: "Notifications")
    if let imageData = image.jpegData(compressionQuality: 0.5) {
        try imageData.write(to: fileURL)
        return true
    }
} catch {
    print(error)
}
return false

Solution 2

following the above example given by vadian the only line you need to save a (Data)file in Document Directory is:

try imageData.write(to: fileURL)

Getting the file path is the interesting part

ex: create the file path

 func createNewDirPath( )->URL{ 

let dirPathNoScheme = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String

    //add directory path file Scheme;  some operations fail w/out it
    let dirPath = "file://\(dirPathNoScheme)"
    //name your file, make sure you get the ext right .mp3/.wav/.m4a/.mov/.whatever
    let fileName = "thisIsYourFileName.mov"
    let pathArray = [dirPath, fileName]
    let path = URL(string: pathArray.joined(separator: "/"))

    //use a guard since the result is an optional
    guard let filePath = path else {
        //if it fails do this stuff:
        return URL(string: "choose how to handle error here")!
    }
    //if it works return the filePath
    return filePath
}

call the function:

let shinnyNewURLpath = createNewDirPath( ) 


//write data to file using one line in do/catch operation
do {
   try yourDataObject?.write(to: shinnyNewURLpath)
    } 
catch {
       print("catch error",error.localizedDescription)
 }

Solution 3

I use the following method for creating "Test.txt" file. Hope it helps you.

func createFile() {
    let fileName = "Test"
    let documentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let fileURL = documentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
    print("File PAth: \(fileURL.path)")
}
Share:
82,550
TechChain
Author by

TechChain

I have 4+ of experience of overall experience.Currently working on Hyperledger Fabric blockchain framework. I have strong knowledge of Objective c, Swift.I have developed lot of apps from chat app, finance apps,location & map based apps.

Updated on November 21, 2020

Comments

  • TechChain
    TechChain over 3 years

    I am saving files in a document directory in swift 3 with this code:

    fileManager = FileManager.default
    // let documentDirectory = fileManager?.urls(for: .documentDirectory, in: .userDomainMask).first as String
    var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    path = path + name
    
    let image = #imageLiteral(resourceName: "Notifications")
    let imageData = UIImageJPEGRepresentation(image, 0.5)
    let bool = fileManager?.createFile(atPath: path, contents: imageData, attributes: nil)
    
    print("bool is \(bool)")
    return true
    

    But as you can see, I am not using filemanager to get document directory path as filemanager gives only URL not string.

    Questions:

    • How to get string from file manager?
    • Is there any chance of crash in my code?
  • Jack
    Jack almost 6 years
    A check if fileManager.fileExists(atPath: path) { print("File already there") } Should be there.
  • Khushbu Desai
    Khushbu Desai almost 6 years
    Can i save whole folder with images in document directory ?
  • vadian
    vadian almost 6 years
    @KhushbuDesai Yes, I suppose.
  • Khushbu Desai
    Khushbu Desai almost 6 years
    @vadian Can you please help me with this? I will share my Code, My folder is copied in doc directory but without data.
  • Moondra
    Moondra almost 6 years
    What is going on here: 'let image = #imageLiteral(resourceName: "Notifications")' What does resourceName represent?
  • vadian
    vadian almost 6 years
  • Kheldar
    Kheldar over 4 years
    @jack forums.developer.apple.com/thread/97497 --> "it is generally regarded s incorrect" etc. What's your take on this?