ios - 在使用 Alamofire + suggestedDownloadDestination 下载文件之前检查文件是否已经存在

标签 ios swift alamofire

如何在使用 Alamofire 重新下载之前检查给定文件是否已下载?我正在使用 suggestedDownloadDestination,因此 Alamofire 会自动选择文件名并将其保存在所选目录中,例如 .CachesDirectory。问题是 suggestedDownloadDestination 给出的值属于 DownloadFileDestination 类型,只有通过请求的 响应调用他才会返回 NSURL ,但通过这种方式,如果之前不执行请求,我永远无法知道文件路径。

这是我目前使用 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 上创建一个扩展,例如:

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

现在您可以在选项参数中指定是否要覆盖该文件:

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

关于ios - 在使用 Alamofire + suggestedDownloadDestination 下载文件之前检查文件是否已经存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37327874/

相关文章:

ios - 如何在iPhone的背景模式下获取当前位置?

IOS 7.1,如果目标设备系列设置为 iPad,通用 Storyboard 的常规宽度限制将被忽略

ios - 如何限制for循环中的网络调用次数?

ios - 与 View Controller 内的自定义 UIView 交互

swift - Alamofire 和 SwiftyJSON 错误

swift - 为什么上传 alamofire 后台请求不在后台执行?

ios - Collection View 单元格的内容大小不正确

ios - M1 Mac Xcode 构建完成但 Flutter 项目失败(苹果芯片)

ios - 禁用 UIButton 注册触摸并抛出错误

ios - GPUImage - 尝试在混合过于频繁时过度释放帧缓冲区