我正在使用 Alamofire 从 url 下载文件,我正在获取文件路径,但我无法找到该文件路径
let mjString = "https://wallpaperstock.net/wallpapers/thumbs1/42535.jpg"
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
print("destinationURLForFile *********** \(documentsURL)")
let fileURL = documentsURL.appendingPathComponent("42535.jpg")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(mjString, to: destination).response { response in
// print(response)
if response.error == nil, let imagePath = response.destinationURL?.path {
let image = UIImage(contentsOfFile: imagePath)
self.mjImage.image = image
print("imagePath = \(imagePath)")
}
}
file:///var/mobile/Containers/Data/Application/4CE55219-8244-4021-B113-1BB00B8F5B10/Documents/42535.jpg
如果可能的话,我希望将该文件保存到自定义文件夹中。任何帮助将不胜感激。
我得到的输出是,
file:///var/mobile/Containers/Data/Application/4CE55219-8244-4021-B113-1BB00B8F5B10/Documents/42535.jpg
最佳答案
只是简单的改变
let fileURL = documentsURL.appendingPathComponent("42535.jpg")
到
let fileURL = documentsURL.appendingPathComponent("/yourFolder/42535.jpg")
编辑
您可以使用此函数加载此图像:
func loadImageFromDocumentDirectory(nameOfImage : String, folder: String) -> UIImage {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("\(folder)/\(nameOfImage)")
if FileManager.default.fileExists(atPath: (imageURL.path)) {
if let image = UIImage(contentsOfFile: imageURL.path) {
return image
}
}
}
//Load default image if img doesnt exist.
return UIImage.init(named: "something.jpg")!
}
只需像这样简单地使用它:
imageView.image = loadImageFromDocumentDirectory(nameOfImage : "42535.jpg", folder: "yourFolder")
关于swift - 如何使用 Alamofire 从 URL 下载文件到自定义文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56883414/