2016-04-22 14 views
5

Tôi nhận được nhiều danh sách tệp hóa đơn ở chế độ xem bảng của tôi cũng như nhiều nút tải xuống tại mỗi ô. Khi tôi nhấp vào một trong số đó, tệp sẽ tải xuống tệp hóa đơn.Nhưng, vấn đề là tên tệp phản hồi của máy chủ được đề xuất là "invoice.pdf" ở mọi tệp tôi đã tải xuống. Do đó, tôi cần phải chỉnh sửa tên tệp theo cách thủ công trước khi tôi lưu vào tài liệu sau khi tệp được tải xuống. Do đó, cách chỉnh sửa tên tệp theo cách thủ công sau khi nó được tải xuống thành công và lưu nó vào tài liệu dưới dạng tạm thời mà không cần sử dụng Alamofire.Request.suggestedDownloadDestination.Đặt tên tệp đích tùy chỉnh của Alamofire thay vì sử dụng đề xuấtDownloadDestination

Đây là chức năng tải xuống của tôi.

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

Đây là chế độ xem bảng sẽ kiểm tra tệp đã tải xuống và khi nhấp vào, được hiển thị trên tính năng mở.

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

Vì vậy, câu hỏi của tôi là simple.I chỉ không muốn sử dụng mã

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

bởi vì nó sử dụng response.suggestedfilename.And Tôi muốn lưu tên file bằng tay trên xem bảng chọn xin vui lòng không nhớ rằng tôi đăng một số mã trong câu hỏi của tôi bởi vì tôi muốn tất cả mọi người nhìn thấy nó rõ ràng.

Trả lời

7

Đích đến thuộc loại (NSURL, NSHTTPURLResponse) -> NSURL. vì vậy bạn có thể làm điều gì đó như

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

này nhanh chóng 3,0 nó 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) 
    } 
} 

để biết thêm đi đến Alamofire

+0

Cảm ơn bạn đã trả lời chi tiết hơn. –

+0

chào mừng bạn :) – Sahil

+0

cách viết giống như vậy trong nhanh chóng 3.0? –

Các vấn đề liên quan