我使用urlsession委托下载2个音频。在下载第一个音频时可以正常工作,但是在下载第二个音频时,则音频会从缓存中移到缓存中,同时从缓存移至内部存储文件时,错误音频已经退出。
此方法用于下载音频。
func downloadPracticeTest(index : Int) {
if !Utile.isInternetAvailable() {
self.showAlert(title: Utile.getLocalizedString(key: Constants.ApiErrorTitle.noInternetTitle), message: Utile.getLocalizedString(key: Constants.ApiErrorMessage.errorNoInternetMediaDownload))
return
}
if isDownloadViewShown == false {
self.showDownloadView()
isDownloadViewShown = true
}
let arrayAudioUrl = getTheAudioUrlList()
let urlObject = URL(string: arrayAudioUrl[index])
let audioPath = Utile.getDocumentDirectoryForAudio()
self.destinationUrl = nil
self.destinationUrlString = nil
self.destinationUrlString = (audioPath.appendingPathComponent((urlObject?.lastPathComponent)!)).description
self.destinationUrl = audioPath.appendingPathComponent((urlObject?.lastPathComponent)!)
print(self.destinationUrl as Any)
//Check Audio already exist or not
if self.fileManager.fileExists(atPath: self.destinationUrl?.path ?? "") {
print("Exist")
let arrayAudioUrl = self.getTheAudioUrlList()
//if all audio is not downloaded
if (self.audioIndex < arrayAudioUrl.count) {
self.destinationUrl = nil
self.destinationUrlString = nil
self.destinationUrlString = (audioPath.appendingPathComponent((urlObject?.lastPathComponent)!)).description
self.destinationUrl = audioPath.appendingPathComponent((urlObject?.lastPathComponent)!)
self.downlProgress = self.downlProgress + Double((100/arrayAudioUrl.count)*self.audioIndex)
self.downloadPracticeTest(index: self.audioIndex)
self.audioIndex = self.audioIndex + 1
//if all audio is downloaded
} else {
self.startTestAfterAudioDownloaded()
}
//if audio not present
} else {
self.destinationUrl = nil
self.destinationUrlString = nil
self.destinationUrlString = (audioPath.appendingPathComponent((urlObject?.lastPathComponent)!)).description
self.destinationUrl = audioPath.appendingPathComponent((urlObject?.lastPathComponent)!)
self.downlProgress = self.downlProgress + Double(25*self.audioIndex)
self.downloadsSession.downloadTask(with: URL(string: arrayAudioUrl[index])!).resume()
}
}
委托方法是这个
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("success")
let arrayAudioUrl = getTheAudioUrlList()
if (audioIndex < arrayAudioUrl.count) {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: location.path) {
print("Exixt")
do {
if let url = destinationUrlString {
// after downloading your file you need to move it to your destination url
try FileManager.default.moveItem(at: location, to: URL(string: url)!)
//delete the downloaded file from the temp folder after moving to new location
Utile.deleteFile(path: location)
}
print("File moved to documents folder")
} catch {
print("\(error)")
}
}