我尝试下载音频文件(M4A),并想在我的应用程序中播放它,我成功完成了该操作,然后将其移至该应用程序的缓存文件夹中。当我从下载的位置播放该文件时,它只能运行一次,当我关闭该应用程序并重新打开它时,iOS不会在关闭该应用程序之前在保存该文件的URL上播放音频文件。如果我通过设备和模拟器导入容器,则表明该文件存在,但URL不起作用。我没有什么问题。请帮助
func getAudio () {
if let audioUrl = songURL {
// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
print(destinationUrl)
// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
print("The file already exists at path")
// if the file doesn't exist
} else {
// you can use NSURLSession.sharedSession to download the data asynchronously
let urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue())
let downloadTask = urlSession.downloadTask(with: audioUrl)
downloadTask.resume()
}
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("downloadLocation:", location)
// create destination URL with the original pdf name
guard let url = downloadTask.originalRequest?.url else { return }
let documentsPath = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0]
let destinationURL = documentsPath.appendingPathComponent(url.lastPathComponent)
// delete original copy
try? FileManager.default.removeItem(at: destinationURL)
// copy from temp to Document
do {
try FileManager.default.copyItem(at: location, to: destinationURL)
self.songURL = destinationURL
self.downloaded = true
} catch let error {
print("Copy Error: \(error.localizedDescription)")
}
}
下载文件后,我得到以下URL路径:file:///var/mobile/Containers/Data/Application/EDF4365C-59B4-4FCA-9E35-BF4FCD667134/Library/Caches/SoundHelix-Song-1.mp3
对于一个会话的应用程序运行正常(直到该应用程序处于活动状态)。
您无法将文件直接复制到.libraryDirectory
,例如尝试尝试使用文档目录.documentDirectory
let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
旁注,您真的需要使用您拥有的url
变量吗?直接使用location
let destinationURL = documentsPath.appendingPathComponent(location.lastPathComponent)