Miguel Ruivo
Miguel Ruivo

Reputation: 17746

Temporary files are being removed during execution on iOS

Surprisingly, and after some time debugging this, I've found that my app is purging files from tmp directory after 1 minute or so, without any other user action, even while the app is running on the foreground.

Accordingly to the docs, temporary directory should keep the files during app execution and only remove it afterwards or at most on its startup.

I don't want to move/copy to caches directory as workaround here, I'm more surprised about why is this actually happening. If that helps, I'm picking from Files app (using UIDocumentPickerViewController).

To make it even better, sometimes there are files that persist for a long time there, even though they are older than the others that are removed instantly after picking. This can result in bad access because your user selects a file, go grab a coffee while the app is still running, and then presses the button to upload it somewhere or whatever and the file is gone.

I can replicate it everytime with a simple app.

Upvotes: 3

Views: 1564

Answers (1)

EJZ
EJZ

Reputation: 1256

After working with temp files a bit, I don't believe this is a bug, it is a feature for temporary files to be deleted when not opened for a period of time. I do believe you can manage that more directly by differentiating between normal and temporary files. As per a much more detailed article here, you can use the ManagedURL protocol to fix your issue:

public protocol ManagedURL {
    var contentURL: URL { get }
    func keepAlive()
}

public extension ManagedURL {
    public func keepAlive() { }
}

extension URL: ManagedURL {
    public var contentURL: URL { return self }
}

To keep the background operation alive:

URLSession.shared.uploadTask(with: request, fromFile: fileToUpload.contentURL) { _, _, _ in
    temporaryFile.keepAlive()
}

Upvotes: 1

Related Questions