Search code examples
iosswiftnsfilemanagernsdocumentdirectory

Delete files from directory inside Document directory?


I have created a Temp directory to store some files:

//MARK: -create save delete from directory
func createTempDirectoryToStoreFile(){
    var error: NSError?
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentsDirectory: AnyObject = paths[0]
    tempPath = documentsDirectory.stringByAppendingPathComponent("Temp")

    if (!NSFileManager.defaultManager().fileExistsAtPath(tempPath!)) {

        NSFileManager.defaultManager() .createDirectoryAtPath(tempPath!, withIntermediateDirectories: false, attributes: nil, error: &error)
   }
}

It's fine, now I want to delete all the files that are inside the directory... I tried as below:

func clearAllFilesFromTempDirectory(){

    var error: NSErrorPointer = nil
    let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
    var tempDirPath = dirPath.stringByAppendingPathComponent("Temp")
    var directoryContents: NSArray = fileManager.contentsOfDirectoryAtPath(tempDirPath, error: error)!

    if error == nil {
        for path in directoryContents {
            let fullPath = dirPath.stringByAppendingPathComponent(path as! String)
            let removeSuccess = fileManager.removeItemAtPath(fullPath, error: nil)
        }
    }else{

        println("seomthing went worng \(error)")
    }
}

I notice that files are still there... What am I doing wrong?


Solution

  • Two things, use the temp directory and second pass an error to the fileManager.removeItemAtPath and place it in a if to see what failed. Also you should not be checking if the error is set but rather whether a methods has return data.

    func clearAllFilesFromTempDirectory(){
    
        var error: NSErrorPointer = nil
        let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
        var tempDirPath = dirPath.stringByAppendingPathComponent("Temp")
        var directoryContents: NSArray = fileManager.contentsOfDirectoryAtPath(tempDirPath, error: error)?
    
        if directoryContents != nil {
            for path in directoryContents {
                let fullPath = dirPath.stringByAppendingPathComponent(path as! String)
                if fileManager.removeItemAtPath(fullPath, error: error) == false {
                    println("Could not delete file: \(error)")
                }
            }
        } else {
            println("Could not retrieve directory: \(error)")
        }
    }
    

    To get the correct temporary directory use NSTemporaryDirectory()