在使用Alamofire +建议的下载位置下载文件之前,检查文件是否已存在 [英] Check if a file already exists before downloading it with Alamofire + suggestedDownloadDestination

查看:323
本文介绍了在使用Alamofire +建议的下载位置下载文件之前,检查文件是否已存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Alamofire重新下载给定文件之前,如何检查给定文件?我使用的是 suggestedDownloadDestination ,因此Alamofire将自动选择文件名并将其保存在所选目录中,例如 .CachesDirectory 。问题是 suggestedDownloadDestination 给出的值是 DownloadFileDestination 类型,该值将返回 NSURL 仅通过调用请求的响应来给他打电话,但是以这种方式,我以前不执行请求就无法知道文件路径。

How can I check if a given file has been already downloaded before re-downloading it by using Alamofire? I'm using suggestedDownloadDestination so Alamofire will automatically choose the name of the file and save it in the choosen directory, for example the .CachesDirectory. The problem is that the value given by suggestedDownloadDestination is of type DownloadFileDestination which will return a NSURL only by calling him with the request's response, but in this way I could not ever know the file path without performing a request before.

这是我目前使用Alamofire下载文件的代码:

This is the code I currently use to download a file with Alamofire:

Alamofire.download(.GET, downloadLink, destination: destination).progress {
                    bytesRead, totalBytesRead, totalBytesExpectedToRead in

                    }.response {
                        request, response, data, error in

                        guard error == nil else {
                            return
                        }

                        // This will give me the file path but we're already in a Request!
                        print("\(destination(NSURL(string: "")!, response!))")
                }

我想念的是什么?

推荐答案

不确定您是否确定了这一点,但您可以通过 Alamofire.DownloadRequest 创建扩展名,例如:

Not sure if you figured this out yet, but you can create an extension over Alamofire.DownloadRequest like:

extension Alamofire.DownloadRequest {
    open class func suggestedDownloadDestination(
        for directory: FileManager.SearchPathDirectory = .documentDirectory,
        in domain: FileManager.SearchPathDomainMask = .userDomainMask,
        with options: DownloadOptions)
        -> DownloadFileDestination
    {
        return { temporaryURL, response in
                let destination = DownloadRequest.suggestedDownloadDestination(for: directory, in: domain)(temporaryURL, response)
            return (destination.destinationURL, options)
        }
    }
}

现在您可以指定如果要覆盖文件,请在options参数中输入:

Now you can specify in the options parameter if you want the file to be overwritten:

let destination =  DownloadRequest.suggestedDownloadDestination(for: .cachesDirectory,
                                                                in: .userDomainMask,
                                                                with: [DownloadRequest.DownloadOptions.removePreviousFile])

这篇关于在使用Alamofire +建议的下载位置下载文件之前,检查文件是否已存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆