简体   繁体   English

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

[英]How to download a file from URL using Alamofire to a custom folder

在此处输入图片说明 I'm using Alamofire to a download file from url, I'm getting filepath, but I'm not able to track down that filepath 我正在使用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

I want that file to a custom folder, if it is possible. 如果可能,我希望将该文件保存到自定义文件夹中。 Any help would be appreciated. 任何帮助,将不胜感激。

The Output what i get is, 我得到的输出是

file:///var/mobile/Containers/Data/Application/4CE55219-8244-4021-B113-1BB00B8F5B10/Documents/42535.jpg 文件:///var/mobile/Containers/Data/Application/4CE55219-8244-4021-B113-1BB00B8F5B10/Documents/42535.jpg

Append Path Component 追加路径组件

just simply change 只是改变

let fileURL = documentsURL.appendingPathComponent("42535.jpg")

to

let fileURL = documentsURL.appendingPathComponent("/yourFolder/42535.jpg")

EDIT 编辑

You can load this image with this function: 您可以使用以下功能加载该图像:

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

Just simply use it like: 只需像这样使用即可:

imageView.image = loadImageFromDocumentDirectory(nameOfImage : "42535.jpg", folder: "yourFolder")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM