gpt4 book ai didi

ios - 如何在 Alamofire 4 中下载文件并保存到 Documents 目录?

转载 作者:IT王子 更新时间:2023-10-29 05:29:26 24 4
gpt4 key购买 nike

我正在尝试将 Alamofire4 用于 Swift3。我需要下载 .mp3 文件并将它们保存到 Documents 目录中。当前代码是这样的:

func downloadAudioFromURL(url: String, completion: ((_ status: ResponseStatus, _ audioLocalURL: URL?) -> Void)?) {


let fileManager = FileManager.default
let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let audioFullURL = String.ensureFullURLPath(url)


alamoManager.download(audioFullURL)
.validate { request, response, temporaryURL, destinationURL in

var pathComponent = response.suggestedFilename!
if pathComponent == "m4a.mp4" {
// Due to the old Android audio files without a filename
// Assign a unique name so audio files don't overwrite each other
pathComponent = "\(NSUUID().uuidString).mp4"
}
let localURL = directoryURL.appendingPathComponent(pathComponent)

if response.statusCode == 200 {
completion?(.success, localURL)
} else {
completion?(.failure, nil)
}
return .success
}

.responseJSON { response in
debugPrint(response)
print(response.temporaryURL)
print(response.destinationURL)
}
}

但是我实际上无法在保存后从 localURL 访问文件。我还注意到,对于我尝试下载的不同文件,localURL 将完全相同(也许它们正在覆盖?)。例如:file:///Users/testuser/Library/Developer/CoreSimulator/Devices/D4254AEA-76DD-4F01-80AF-F1AF3BE8A204/data/Containers/Data/Application/29755154-DD21-4D4C-B340-6628607DC053/文件/file1.mp3

知道我在这里做错了什么吗?

将我的代码编辑成如下所示:

func downloadAudioFromURL(url: String, completion: ((_ status: ResponseStatus, _ audioLocalURL: URL?) -> Void)?) {

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

documentsURL.appendPathComponent("Audiofile.mp3")
return (documentsURL, [.removePreviousFile])
}

Alamofire.download(url, to: destination).response { response in

if let localURL = response.destinationURL {

completion?(.success, localURL)

} else {

completion?(.failure, nil)
}

}
}

不过,我该如何检查 m4a.mp4?

最佳答案

为什么要执行 .validate?在当前代码中下载后,您不会存储任何数据。 Alamofire allows you to store a file directly after download:

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendPathComponent("pig.png")

return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}

Alamofire.download(urlString, to: destination).response { response in
print(response)

if response.result.isSuccess, let imagePath = response.destinationURL?.path {
let image = UIImage(contentsOfFile: imagePath)
}
}

顺便说一句,您在 download 方法中提供的下载路径是文档目录的本地 URL,而不是服务器的 URL。

关于ios - 如何在 Alamofire 4 中下载文件并保存到 Documents 目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39869581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com