草庐IT

swift - 设置 Alamofire 自定义目标文件名而不是使用 suggestedDownloadDestination

coder 2023-09-04 原文

我的表格 View 中有许多发票文件列表以及每个单元格中的许多下载按钮。当我单击其中一个时,它将下载发票文件。但是,问题是服务器响应建议的文件名是我下载的每个文件都有“invoice.pdf”。所以,我需要在下载文件后保存到文档之前手动编辑文件名。那么,如何在成功下载后手动编辑文件名并将其保存在文档中作为临时 url,而不使用 Alamofire.Request.suggestedDownloadDestination

这是我的下载功能。

func downloadInvoice(invoice: Invoice, completionHandler: (Double?, NSError?) -> Void) {

guard isInvoiceDownloaded(invoice) == false else {
  completionHandler(1.0, nil) // already have it
  return
}

let params = [
    "AccessToken" : “xadijdiwjad12121”]

// Can’t use the destination file anymore because my server only return one file name “invoice.pdf” no matter which file i gonna download
// So I have to manually edit my file name which i saved after it was downloaded.    
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
// So I have to save file name like that ““2016_04_02_car_invoice_10021.pdf” [Date_car_invoice_timestamp(Long).pdf]
// Please look comment on tableView code

Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders?.updateValue("application/pdf",forKey: "Content-Type")

Alamofire.download(.POST, invoice.url,parameters:params, destination: destination)
      .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
        print(totalBytesRead)
        dispatch_async(dispatch_get_main_queue()) {
          let progress = Double(totalBytesRead) / Double(totalBytesExpectedToRead)
          completionHandler(progress, nil)
        }
      }
      .responseString { response in
        print(response.result.error)
        completionHandler(nil, response.result.error)
    }
  }

这里是表格 View ,它将检查下载的文件,当它点击时,显示在打开的功能中。

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let invoice = dataController.invoices?[indexPath.row] {
  dataController.downloadInvoice(invoice) { progress, error in
    // TODO: handle error
    print(progress)
    print(error)
    if (progress < 1.0) {
      if let cell = self.tableView.cellForRowAtIndexPath(indexPath), invoiceCell = cell as? InvoiceCell, progressValue = progress {
        invoiceCell.progressBar.hidden = false
        invoiceCell.progressBar.progress = Float(progressValue)
        invoiceCell.setNeedsDisplay()
      }
    }
    if (progress == 1.0) {
    // Here where i gonna get the downloaded file name from my model.
        // invoice.filename = (Assume “2016_04_02_car_invoice_10021”)
        if let filename = invoice.filename{
            let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
            let docs = paths[0]
            let pathURL = NSURL(fileURLWithPath: docs, isDirectory: true)
            let fileURL = NSURL(fileURLWithPath: filename, isDirectory: false, relativeToURL: pathURL)

            self.docController = UIDocumentInteractionController(URL: fileURL)
            self.docController?.delegate = self
            if let cell = self.tableView.cellForRowAtIndexPath(indexPath) {
                self.docController?.presentOptionsMenuFromRect(cell.frame, inView: self.tableView, animated: true)
                if let invoiceCell = cell as? InvoiceCell {
                    invoiceCell.accessoryType = .Checkmark
                    invoiceCell.setNeedsDisplay()
                }
            }
        }
    }
  }
}
}

所以,我的问题很简单。我只是不想使用该代码

let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)

因为它使用 response.suggestedfilename。我想在选定的表格 View 单元格数据上手动保存文件名。有什么帮助吗?请不要介意我在我的问题中发布了一些代码,因为我希望每个人都能清楚地看到它。

最佳答案

目标是 (NSURL, NSHTTPURLResponse) -> NSURL 类型。所以你可以做这样的事情

 Alamofire.download(.POST, invoice.url,parameters:params, destination: { (url, response) -> NSURL in

    let pathComponent = "yourfileName"

    let fileManager = NSFileManager.defaultManager()
    let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let fileUrl = directoryURL.URLByAppendingPathComponent(pathComponent)
    return fileUrl
    })
  .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
    print(totalBytesRead)
    dispatch_async(dispatch_get_main_queue()) {
      let progress = Double(totalBytesRead) / Double(totalBytesExpectedToRead)
      completionHandler(progress, nil)
    }
    }
    .responseString { response in
      print(response.result.error)
      completionHandler(nil, response.result.error)
  }
}

swift 3.0

在 swift 3.0 中它是 DownloadFileDestination

 Alamofire.download(url, method: .get, to: { (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
  return (filePathURL, [.removePreviousFile, .createIntermediateDirectories])
})
 .downloadProgress(queue: utilityQueue) { progress in
    print("Download Progress: \(progress.fractionCompleted)")
}
.responseData { response in
    if let data = response.result.value {
        let image = UIImage(data: data)
    }
}

有关更多信息,请访问 Alamofire

关于swift - 设置 Alamofire 自定义目标文件名而不是使用 suggestedDownloadDestination,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36785555/

有关swift - 设置 Alamofire 自定义目标文件名而不是使用 suggestedDownloadDestination的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  7. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  10. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

随机推荐