2016-03-01 45 views
2

我如何在alamofireswift 2.1中保留已下载文件的轨道或记录,以便我不必再次下载相同的文件?我们是否有任何本地方法,由alamofire提供,或者我们必须在下载目录中的任何文件之前进行检查,如果我们已经有了那个名字的文件吗?我是如何用适当的方法用`alamofire`跟踪已经下载的文件

做到这一点困惑,如果有人将清除我对这样的困惑,然后它会为我有这样的帮助的感谢

UPDATE:

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

    } 

以上更新试图得到alamofire生成suggestedFileName,但有一个问题,当我试图得到sugestedFileName像这样:suggestedFileName = (request?.response?.suggestedFilename)! in viewdidload因为没有suggestedFileName因为没有suggestedFileName,因为下载尚未开始,所以我questio n是我怎么能从response开始下载之前得到suggestedFileName

回答

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 
} 
+0

是啊,我得到了相同的解决方法我试图让建议的文件名,但有一个问题,我不知道如何处理,请参阅我的更新问题 –

+1

是的,你必须在每次下载之前进行检查。 Alamofire不提供原生的方式来做到这一点。 – Quantaliinuxite

+0

嘿谢谢:)我欣赏这 –