Home > other >  Directory keeps changing
Directory keeps changing

Time:09-30

I have been trying to create a file in my user document directory, writing to it and retrieving it. Works fine whilst the app is running but if I close the app and reload it the user document directory changes and my file is no loner available.

import UIKit
import Foundation
//
// [1]
//do {
    let fileName = "Test"
    let exTension = "txt"
    let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    let fileUrl = documentDirectory.appendingPathComponent(fileName).appendingPathExtension(exTension)
    if FileManager.default.fileExists(atPath: fileUrl.path) {
        print(" [1] FILE AVAILABLE \(fileUrl)")
        // Reading it back from the file
        var inString = ""
        do {
            inString = try String(contentsOf: fileUrl)
        } catch {
            assertionFailure("Failed reading from URL: \(fileUrl), Error: "   error.localizedDescription)
        }
        print("[1] Read from the file: \(inString)")
    } else {
        print("[2] File not Present. Will Create it. \(fileUrl)")
// [3] Writing to the file named Test
        let outString = "Hello. I am line 1 of the file"
        do {
            try outString.write(to: fileUrl, atomically: true, encoding: .utf8)
        } catch {
            assertionFailure("Failed writing to URL: \(fileUrl), Error: "   error.localizedDescription)
        }
// Reading it back from the file
        var inString = ""
        do {
            inString = try String(contentsOf: fileUrl)
        } catch {
            assertionFailure("Failed reading from URL: \(fileUrl), Error: "          
error.localizedDescription)
        }
        print("[3] Read from the file: \(inString)")
    }

CodePudding user response:

Bear in mind that the building a new version of your app from scratch and installing it from Xcode (particularly to the simulator) may delete your app's sandboxed directories.

Simply changing some source files and re-running the app should not erase everything, but a clean and rebuild probably will.

CodePudding user response:

When I was developing the video caching app. I realize that the full path your get from saving files to document folder is session-based. So if you kill app, and relaunch it, the document path will be changed. BUT your files and your subfolders won't be changed.

So you can save the "Relative path of file or File unique name" to use it as an identifier to "search" in the document folder,...

Here is the useful extension for this problem, check the last function:

import Foundation

extension FileManager {
    static func clearTempFile(at url: URL) {
        print("Start clear temp file: \(url.absoluteString)")
        do {
            try FileManager.default.removeItem(at: url)
        } catch {
            print(error.localizedDescription)
        }
    }
    
    static func clearTmpDirectory() {
        do {
            let tmpDirectory = try FileManager.default.contentsOfDirectory(atPath: NSTemporaryDirectory())
            try tmpDirectory.forEach { file in
                let path = String.init(format: "%@%@", NSTemporaryDirectory(), file)
                try FileManager.default.removeItem(atPath: path)
            }
        } catch {
            print(error)
        }
    }
    
    static func clearAllFileInDocument(with path: String) {
        let fileManager = FileManager.default
        let myDocuments = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
        let diskCacheStorageBaseUrl = myDocuments.appendingPathComponent(path)
        guard let filePaths = try? fileManager.contentsOfDirectory(at: diskCacheStorageBaseUrl, includingPropertiesForKeys: nil, options: []) else { return }
        for filePath in filePaths {
            try? fileManager.removeItem(at: filePath)
        }
    }
    
    static func checkAllFileInDocument(with path: String) {
        let fileManager = FileManager.default
        let myDocuments = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
        let diskCacheStorageBaseUrl = myDocuments.appendingPathComponent(path)
        guard let filePaths = try? fileManager.contentsOfDirectory(at: diskCacheStorageBaseUrl, includingPropertiesForKeys: nil, options: []) else { return }
        for filePath in filePaths {
            print(filePath.absoluteString)
        }
    }
    
    /// path is your sub/child folder, basePath is fileName with extension: abc.jpg, def.mp4...
    static func searchFileInDocument(contain path: String, in basePath: String) -> URL? {
        let fileManager = FileManager.default
        let myDocuments = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
        let diskCacheStorageBaseUrl = myDocuments.appendingPathComponent(basePath)
        guard let filePaths = try? fileManager.contentsOfDirectory(at: diskCacheStorageBaseUrl, includingPropertiesForKeys: nil, options: []) else { return nil }
        for filePath in filePaths {
            if filePath.absoluteString.contains(path) {
                return filePath
            }
        }
        return nil
    }
}
  • Related