In my iOS project, I need to download a file at a specific location on the device, so I can start reading it while it's still being downloaded.
My goal here is to stream an audio file from the start, but I need that audio file to be saved locally at its final location (I don't want the file to be saved in a temporary folder during the download, and then moved to its final location when the download is complete, which apparently is the default behavior).
So here is what I've tried so far:
private var observation: NSKeyValueObservation?
func downloadAudioFile()
{
let url: URL = URL(string: "https://www.demo.com/audiofile.ogg")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
if (error != nil)
{
print(error)
}
else
{
print("download complete")
}
}
observation = task.progress.observe(\.fractionCompleted) {(progress, _) in
print("progression : \(progress)")
}
task.resume()
}
But since I'm quite a beginner in iOS, I don't know how to save the downloaded data while it's downloading.
How can I achieve that?
Thanks.