'iOS - Calling bookmarkData() from a different thread returns an error

I am using a download session task (AVDownloadTask) to download a stream. To do this, I use a AVAggregateAssetDownloadTask in the init, the delegateQueue is set to main.

I create and resume session tasks from a separate thread:

func doSomething async {
   Task {
    //Task setup here resulting in a let called task
    task.resume()

   }
}

Now, in the delegate, I have:

   public func urlSession(
        _ session: URLSession,
        aggregateAssetDownloadTask: AVAggregateAssetDownloadTask,
        willDownloadTo location: URL
    ) {
        
        print("Location: \(location.path)")
        do {
            let data = (try location.bookmarkData())
            print("Generated data with length \(data.count)")
            
        } catch {
            print("Ooops, an error occurred:  \(error)")
        }

The problem is, when I run the code I get an error:

Error Domain=NSCocoaErrorDomain Code=260 "The file couldn’t be opened because it doesn’t exist."

I am not sure why this is the case. My code is basically exactly the same as a sample from Apple, however If I generate the task from a different thread on that sample, I can reproduce my error.

This leads me to believe, there is a problem (probably with security scoping, but doesn't make sense to me) when trying to access a URL from a different thread in order to generate a bookmark. Has anyone experience this? Any ideas how it can be fixed?

Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source