Home > Back-end >  Download PDF from API Return Swift Document Can Not Be Shown Alert
Download PDF from API Return Swift Document Can Not Be Shown Alert

Time:06-13

The API I am using has 3 parameters year month and salaryType.

When I enter those parameters to my URL

if let url = URL(string: "https://rip.rtuk.gov.tr/workplacebackend/api/Employee/GetPayroll?yil=\(year)&ay=\(month)&maasturu=\(salaryType)")

URL becomes

"https://rip.rtuk.gov.tr/workplacebackend/api/Employee/GetPayroll?yil=2020&ay=2&maasturu=1"

When I enter this URL with Auth and Token it returns a pdf file. How should I modify my getPayroll so that I can download pdf after the request?

 func getPayroll(year: Int, month: Int, salaryType: Int, completion: @escaping (String) -> ()) {
    if let url = URL(string: "https://rip.rtuk.gov.tr/workplacebackend/api/Employee/GetPayroll?yil=\(year)&ay=\(month)&maasturu=\(salaryType)") {
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.addValue("Basic \(authToken)", forHTTPHeaderField: "Authorization")
        request.addValue(workingToken, forHTTPHeaderField: "token")
        let task = URLSession.shared.downloadTask(with: request) { (localURL, urlResponse, error) in
            if let localURL = localURL {
                if let string = try? String(contentsOf: localURL) {
                    completion(string)
                }
            }
        }
        task.resume()
    }
}

So when I tap on a cell I want to show an alert, download and then open pdf

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch cellType(rawValue: selected.title) {
    case .salary:
        selectedPayment = (payment?[indexPath.row])!
        RtukNetworkManager.shared.getPayroll(year: selectedPayment.year, month: selectedPayment.month, salaryType: selectedPayment.paymentType) { filePath in
             DispatchQueue.main.async {
                self.displayDownloadAlert(filePath)
            }
        }

 func downloadFile(path: String) {
    let donwloadManager = FileDownloadManager()
    donwloadManager.downloadFile(path: path, viewController: self)
}

When I tap on a cell getting an error as an alert

Error The document can not be shown

CodePudding user response:

this will save pdf file to url and also check if already downloaded

func getPayroll(year: Int, month: Int, salaryType: Int, completion: @escaping ((URL?) -> ())) {
            let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            
            let parameters: [String: Int] = ["yıl": year, "ay": month, "maasturru": salaryType]
            if let url = URL(string: "https://rip.rtuk.gov.tr/workplacebackend/api/Employee/GetPayroll?yil=\(year)&ay=\(month)&maasturu=\(salaryType)") {
                
                let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)
                if FileManager().fileExists(atPath: destinationUrl.path) {
                    print("File already exists [\(destinationUrl.path)]")
                    completion(destinationUrl)
                }
                var request = URLRequest(url: url)
                request.httpMethod = "GET"
                request.addValue("Basic \(authToken)", forHTTPHeaderField: "Authorization")
                request.addValue(workingToken, forHTTPHeaderField: "token")
                let session = URLSession(configuration: .default)
                let task = session.dataTask(with: request) { (data, response, error) in
                    if error == nil {
                        if let response = response as? HTTPURLResponse  {
                            if response.statusCode == 200 {
                                if let data = data  {
                                    if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic)
                                    {
                                        completion(destinationUrl)
                                    }
                                    else
                                    {
                                        completion(destinationUrl)
                                    }
                                }
                            }
                        }
                    } else {
                        print(error?.localizedDescription)
                        completion(nil)
                    }
                }
                task.resume()
            }
        }

after that call your to download

RtukNetworkManager.shared.getPayroll(year: selectedPayment.year, month: selectedPayment.month, salaryType: selectedPayment.paymentType) { filePath in  
     if let url = filePath {
       self.displayDownloadAlert(url.lastPathComponent)
       showPdf(url:url)
     }
            
  }

to show pdf

 func showPdf(url:URL) {
                let pdfView = PDFView(frame: CGRect(x:100,y:100,width:200,height:200))
                let pdfDocument = PDFDocument(url: url)) 
     
                pdfView.autoresizesSubviews = true
                pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin]
                pdfView.displayDirection = .vertical
                pdfView.autoScales = true
                pdfView.displayMode =  .singlePage 
                pdfView.displaysPageBreaks = true
                pdfView.document = pdfDocument
                pdfView.maxScaleFactor = 4.0
                pdfView.minScaleFactor =     pdfView.scaleFactorForSizeToFit
                pdfView.usePageViewController(true, withViewOptions: [:])
               view.addSubview(pdfView)

  }

also import PDFKit PDFView use for displaying pdf

  • Related