URLSession.uploadTask withFile When can file be deleted

Since I am uploading in the background, I need to save the request body off in a file. The documentation says this gets copied to a temporary storage area and uploaded from there. When can I delete the temporary file I generated? Deleting it just after the call to

session.uploadTask(with: request, fromFile: filePath)

seems to be a race condition where I will occasionally get a sharing violation deleting the file.
Do I have to keep my temporary file around until DidCompleteWithError or DidReceiveData is called?

I ask because I'm uploading an existing photo, so I have to generate a multi-part form file with the photo embedded, then iOS makes a copy of that file. This results in having the photo in storage on the device three times. We are uploading photos from an Event so there will be several hundred, so Im worried about device storage running out.

Todd

Answered by robnotyou in 698344022

When uploading in the background, the temporary file should be deleted (on the main thread) in the upload task's completion handler.

That is, the upload task must have finished (with success or failure) before you delete the temporary file.

In URLSessionTaskDelegate, that would be in:

  • urlSession(_:task:didCompleteWithError:)

(Of course, if there was an error, you might want to try again.)

Try deleting the file right after you call resume() on the task.

When uploading in the background, the temporary file should be deleted (on the main thread) in the upload task's completion handler.

That is, the upload task must have finished (with success or failure) before you delete the temporary file.

In URLSessionTaskDelegate, that would be in:

  • urlSession(_:task:didCompleteWithError:)

(Of course, if there was an error, you might want to try again.)

Did you solve this, @CentricsDev?

I'd like to know this as well. It doesn't seem to documented properly.

It doesn't seem to documented properly.

Right. In the absence of documentation saying otherwise, the only reasonable option is to ensure that the file stays around until the request is complete, that is, until urlSession(_:task:didCompleteWithError:) is called.

I’ve looked into this in the past and there have been a bunch of changes in this space (up to and including the session using clonefile to maintain its own copy). However, without a specific behaviour being documented, those are just implementation details.

If you’d like to delete the file sooner, I encourage you to file an enhancement request for that. It’s possible that the resolution will be a simple documentation change, but I’m not 100% confident of that. I suspect that there are edge cases that I’m not aware of.

Please post your bug number, just for the record.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

URLSession.uploadTask withFile When can file be deleted
 
 
Q