ios - 如果此文件已存在,则取消 Alamofire 文件下载

标签 ios swift alamofire request-cancelling

如果下载的文件已经存在于文档文件夹中,如何取消 Alamofire 请求?

请求代码如下:

Alamofire.download(.GET, fileUrls[button.tag], destination: { (temporaryURL, response) in
    if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
        let fileURL = directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
        self.localFilePaths[button.tag] = fileURL
        if NSFileManager.defaultManager().fileExistsAtPath(fileURL.path!) {
            NSFileManager.defaultManager().removeItemAtPath(fileURL.path!, error: nil)
        }
        return fileURL
    }
    println("temporaryURL - \(temporaryURL)")
    self.localFilePaths[button.tag] = temporaryURL
    return temporaryURL
}).progress { _, totalBytesRead, totalBytesExpectedToRead in
    println("\(totalBytesRead) - \(totalBytesExpectedToRead)")
    dispatch_async(dispatch_get_main_queue()) {
        self.progressBar.setProgress(Float(totalBytesRead) / Float(totalBytesExpectedToRead), animated: true)

        if totalBytesRead == totalBytesExpectedToRead {
            self.progressBar.hidden = true
            self.progressBar.setProgress(0, animated: false)
        }
    }
}.response { (_, _, data, error) in
    let previewQL = QLReaderViewController()
    previewQL.dataSource = self
    previewQL.currentPreviewItemIndex = button.tag
    self.navigationController?.pushViewController(previewQL, animated: true)
}

我还尝试创建一个请求变量 var request: Alamofire.Request? 然后取消 request?.cancel() 如果该文件存在但它不起作用。

有人可以帮我解决这个问题吗?

最佳答案

IMO 你不应该首先取消请求而不是取消请求。在启动 Alamofire 请求之前,您应该进行文件检查。

如果您确实觉得需要开始请求,您随时可以在开始请求后立即取消。

var shouldCancel = false

let request = Alamofire.request(.GET, "some_url") { _, _ in
        shouldCancel = true
    }
    .progress { _, _, _ in
        // todo...
    }
    .response { _, _, _ in
        // todo...
    }

if shouldCancel {
    request.cancel()
}

关于ios - 如果此文件已存在,则取消 Alamofire 文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32841455/

相关文章:

ios - 添加 NSManagedObjects 子类时出错

ios - 带闭包的 UIGestureRecognizer

ios - 根据我的媒体查询禁用 JS

ios - Alamofire 4 多部分请求上传进度

iOS swift Alamofire解析,创建泛型类解析json数据

ios - 在 iPhone 应用程序中使用国际键盘

ios - NSNotificationCenter addObserver 在 Swift 中调用私有(private)方法

ios - 为什么 tableView 的 FooterView 在 vi​​ewDidLoad() 中不存在,如何解决?

ios - 在重定向之前停止 NSURL 连接,同时获取重定向 URL

ios - 没有占位符图像的 UITableViewCell 中的 AlamofireImage af_setImageWithURL