iosswiftfileswift5userdefaults

How to save firmware file selected from document picker in swift


I am trying to upgrade the radar using a firmware file. I am selecting a firmware file using a document picker and saving its path to a singleton class variable. But the problem is when I go to the background and return it shows that the file does not exist in that path. How can I resolve the issue? The code for saving the path is `

    let file = urls[0]
    do {
         let filePath = file.path

         self.firmwareLocalfilePath = filePath

         SessionController.sharedController.filePath = self.firmwareLocalfilePath

'

Here SessionController.sharedController.filePath is my singleton variable. The condition to check file availability is

if FileManager().fileExists(atPath: self.firmwareLocalfilePath!)

When I go to the background and come back it is getting that
"File does not exist [/private/var/mobile/Containers/Data/Application/92D35520-C1E8-44DD-960E-B7024E8602E8/tmp/com.houston-radar.app-Inbox/dc300b04_v297.frm]"

There are lots of other kinds of stuff there that's why I am not uploading the full code. The code is related to the file I wrote here. How can I resolve this issue? Can I save the file somewhere like userdefault. I googled it a lot but did not get any solution. Thank you for your help


Solution

  • Your file is loaded/stored in a temporary directory. iOS itself decides when it wants to remove files from that directory. It appears you're currently experiencing it while going to the background. I would recommend trying to initially save it in a non temporary directory, but I'm not sure if that's possible. Therefore, you could try to move it from the temporary folder to a non temporary folder, such as the Application Support folder.

    do {
        // 1. Get the firmware URL at which the firmware file is located 
        //    (your current temporary URL)
        let firmwarePath: URL = NSURL.fileURL(withPath: localFilePath)
    
        // 2. Create a persistent URL
        let newFirmwarePath = try FileManager.default
            .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
            .appendingPathComponent(firmwarePath.lastPathComponent)
    
        // 3. Try moving the file from the temporary directory to a non temporary directory
        //.   This is where we move it from the /tmp to /Application Support
        try FileManager.default.moveItem(at: firmwarePath, to: newFirmwarePath)
    
        // 4. Lastly, update your static property
        SessionController.sharedController.filePath = newFirmwarePath.path
    } catch {
        print(error)
    }
    

    I feel like storing the path this way is very error prone, so I can only recommend trying to figure out an alternative way to communicate the file/path/location. But I suppose this should work