如何使用Alamofire从URL将文件下载到自定义文件夹

时间:2019-07-04 08:10:05

标签: swift file download alamofire

enter image description here我正在使用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

1 个答案:

答案 0 :(得分:1)

Append Path Component

只需更改

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")