3

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?

Elena
  • 829
  • 8
  • 20
  • `.createFileAtPath` returns a bool indicating if the operation completed successfully, you should check that. – Eric Aya Jan 19 '16 at 11:29
  • I checked now and it returns `false` which is not surprise. Any other suggestions pleeaase? – Elena Jan 19 '16 at 13:11
  • Well, now that we know that the second snippet is not the culprit, we can focus on the first one. Just looking at it my guess is that `filePath` is not correct. But it's just my guess, *you* have to debug a bit more. – Eric Aya Jan 19 '16 at 13:14
  • Thanks a lot, I`ll keep searching – Elena Jan 19 '16 at 13:20

1 Answers1

5

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.

Community
  • 1
  • 1
Elena
  • 829
  • 8
  • 20