Search code examples
swift2nsfilemanagernsdocumentdirectory

Swift. Can`t save file to DocumentDirectory. Whats wrong?


Here`s my code:

let fileName = "someFileName"

func saveDataToFile(urlStr:String){
    let url = NSURL(string: urlStr)
    var data:NSData!
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let directory = paths[0]
    let filePath = directory.stringByAppendingPathComponent(self.fileName)
    print(filePath)//prints /Users/.../Library/Developer/CoreSimulator/Devices/1013B940-6FAB-406B-96FD-1774C670A91E/data/Containers/Data/Application/2F7139D6-C137-48BF-96F6-7579821B17B7/Documents/fileName

    let fileManager = NSFileManager.defaultManager()

    data = NSData(contentsOfURL: url!)
    print(data) // prints a lot of data     
    if data != nil{
        fileManager.createFileAtPath(filePath, contents: data, attributes: nil)
    }

}

Now I want to read this data:

func readDataFromFile(){
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let directory = paths[0]
    let filePath = directory.stringByAppendingPathComponent(self.fileName)
    print(filePath) // prints the same path
    let fileManager = NSFileManager.defaultManager()
    if fileManager.fileExistsAtPath(filePath){
            data = fileManager.contentsAtPath(filePath)
        }else{
            print("*****BAD*****") // always prints this which means that file wasn`t created
        }
}

What`s wrong with the first func? What is the right way to save file to DocumentDirectory?


Solution

  • OK, in this case the answer was following:

    First need to create directory (aka folder) and only after that create file inside that directory.

    Added to code this:

    let fullDirPath = directory.stringByAppendingPathComponent(folderName)
    let filePath = fullDirPath.stringByAppendingPathComponent(fileName)
    
    do{
        try fileManager.createDirectoryAtPath(fullDirPath, withIntermediateDirectories: false, attributes: nil)
    }catch let error as NSError{
        print(error.localizedDescription)
    }
    

    And as I said after this you create your file:

    fileManager.createFileAtPath(filePath, contents: data, attributes: nil)

    Thanks to Eric.D

    Hope someone will find this useful.