Evgeniy Kleban
Evgeniy Kleban

Reputation: 6940

Trying to clear document folder Swift

I use following method to add file (download) to document directory:

 static func downloadFileWithLink(linkString : String){

        // Create destination URL
        let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
        let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile")

        //Create URL to the source file you want to download
        let fileURL = URL(string: linkString)

        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig)

        let request = URLRequest(url:fileURL!)

        let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")
                }

                do {
                    try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                } catch (let writeError) {
                    print("Error creating a file \(destinationFileUrl) : \(writeError)")
                }

            } else {
                print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
            }
        }
        task.resume()

    }

It simply download file to document folder in sandbox. I looked for method that delete files in documents folder, and tried following:

static func deleteFiledInDocDirectory(){

        let fileManager = FileManager.default
        let tempFolderPath = NSTemporaryDirectory()
        do {
            let filePaths = try fileManager.contentsOfDirectory(atPath: tempFolderPath)
            for filePath in filePaths {
                try fileManager.removeItem(atPath: tempFolderPath + filePath)
            }
        } catch {
            print("Could not clear temp folder: \(error)")
        }
    }

However, when i inspect sandbox, downloaded file is still here. How to delete it?

Upvotes: 1

Views: 346

Answers (1)

Paolo
Paolo

Reputation: 3945

In deleteFiledInDocDirectory() you're using NSTemporaryDirectory instead of the documents directory that you originally saved the file to.

Change tempFolderPath to be set using following:

guard let tempFolderPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
    return   // documents directory not found for some reason
}

The full method:

static func deleteFiledInDocDirectory(){
    guard let tempFolderPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first?.absoluteString else {
        return   // documents directory not found for some reason
    }

    let fileManager = FileManager.default

    do {
        let filePaths = try fileManager.contentsOfDirectory(atPath: tempFolderPath)
        for filePath in filePaths {
            try fileManager.removeItem(atPath: tempFolderPath + filePath)
        }
    } catch {
        print("Could not clear temp folder: \(error)")
    }
}

Upvotes: 2

Related Questions