Skip to content

There's a gotcha in this code 😨 #1

@iandundas

Description

@iandundas

Really loved the blog post, however there's actually a gotcha in this approach using continuations.

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)

Unfortunately the location is "use it or lose it" .. before the function exits scope. Otherwise the file at this temporary location no longer exists.

CleanShot 2023-04-12 at 13 47 12@2x
docs

So if we modify ViewModel.saveFile(for episode: Episode, at url: URL) to actually catch the error:

CleanShot 2023-04-12 at 13 48 39@2x

Then the error is revealed:

error: Error Domain=NSCocoaErrorDomain Code=4 "“CFNetworkDownload_45xjff.tmp” couldn’t be moved to “1386867488” because either the former doesn’t exist, or the folder containing the latter doesn’t exist." UserInfo=...., NSUnderlyingError=0x600001f0a550 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

Basically the above function calls continuation?.yield(.success(url: location)) and then returns, before the ViewModel has a chance to actually handle the next event (i.e. before it has a chance to move the file out of the temporary location). So the file is gone.

Quite heartbreaking because this was otherwise a very nice approach. 💔

Not sure if there's a way to tweak it so that the continuation is handled synchronously, I'm not that advanced with async/await yet.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions