使用“alamofire”

时间:2016-03-01 08:35:54

标签: swift alamofire

如何在alamofire swift 2.1中保留已下载文件的跟踪或记录,以便我不必再次下载同一文件?我们是否有alamofire提供的任何原生方法,或者我们必须在下载目录中的任何文件之前进行检查,如果我们已经拥有该名称的文件那么????我对如何以正确的方法实现这一点感到困惑

如果有人会清除我对此的困惑,那么对我来说这将非常有用,谢谢

更新:

        let documentsURL  = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let fileUrl = documentsURL.URLByAppendingPathComponent(suggestedFileName)

    print(fileUrl)

    if !(NSFileManager.defaultManager().fileExistsAtPath(fileUrl.path!)){

        self.suggestedFileName = (self.request?.response?.suggestedFilename)! // here how can i get the suggested download name before starting the download preocess ???

        print("\(destination)")
        request =  Alamofire.download(.GET, "http://contentserver.adobe.com/store/books/GeographyofBliss_oneChapter.epub", destination: destination)
            .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
                print(totalBytesRead)






                // This closure is NOT called on the main queue for performance
                // reasons. To update your ui, dispatch to the main queue.
                dispatch_async(dispatch_get_main_queue()) {
                    print("Total bytes read on main queue: \(totalBytesRead)")

                    self.progressView.setProgress(Float(totalBytesRead) / Float(totalBytesExpectedToRead), animated: true)
                }
            }
            .response { _, _, _, error in
                if let error = error {
                    print("Failed with error: \(error)")
                } else {
                    print("Downloaded file successfully")
                }
        }

    }else {


        print("file already exists")

    }

在上面的更新中我尝试获取由suggestedFileName生成的alamofire,但在尝试获取此sugestedFileName时遇到一个问题:viewdidload中的suggestedFileName = (request?.response?.suggestedFilename)!因为没有suggestedFileName,因为没有suggestedFileName因为下载尚未开始,所以我的问题是如何在开始下载之前从response获取- google.charts.load('current', {'packages':['bar']}); + google.charts.load('43', {'packages':['bar']});

1 个答案:

答案 0 :(得分:1)

根据文档https://github.com/Alamofire/Alamofire#downloading,您可以下载到文件。如果您的文件目标名称是可预测的,您只需检查该文件的内容是否存在。例如,如果您正在下载数据:

if let data = NSData(contentsOfURL: yourDestinationURL) {
  //Do your stuff here
}
else {
  //Download it
}

如果您希望名称之间保持一致,我建议您避开Alamofire建议的目的地并改为:

let path = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)[0] as NSURL
let newPath = path.URLByAppendingPathComponent(fileName)
    Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: { _ in
    newPath //You have to give the destination in this closure. We could say 'return newPath' instead, they're the same thing.
  })
  .progress({ _ in
    //progress stuff
  })
  .response { _, _, data, _ in
    //Handle response once it's all over
}