How to show pdf data from a filestream

1.3k views Asked by At

I am working against a REST API where you can make a call and then receive a image or pdf. I am using URLSession.shared.dataTask to make the call and when there is a image the call is a success (but it takes quite a long time, more then 5 seconds) and I can show the image in a UIImageView. But when there is a pdf, I don't know how to handle the result. The API returns the image / pdf as a ”filestream”.

When I print the data to the console it prints the size (bytes) and its the same size as in the server so in some way I have the correct data, I just don't know how to view the pdf.

I am using swift 3, iOS 10, xcode 8.

1

There are 1 answers

1
Thiha Aung On BEST ANSWER

First of all you may want to ask your question into two part. Please edit it and ask the second part again.

There are two parts in this topic

1. Downloading the PDF and save it in File System

2. Get the pdf that saved in File System and read it using UIWebView or UIDocumentInteractionController

So, I will explain for the first one.

The first one can be done if you use REST HTTP client : Alamofire : Elegant HTTP Networking in Swift. So no need to use URLSession for such case and you will have to write so many lines if you do. It's simple and easy. So, I want you to try it. If you need URLSession instead, leave comment.

So how to download pdf using Alamofire :

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
//.documentDirectory means it will store in Application Document Folder
let fileURL = documentsURL.appendPathComponent("data.pdf")

      return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}

Alamofire.download(urlString, to: destination).response { response in
print(response)

     if response.error == nil, let filePath = response.destinationURL?.path {
           // do anything you want with filePath here.
           // Here what you have to do Step 2. (Read the file that you downloaded)
     }
}

This download procedure doesn't include requesting download link with encoded parameters. It was just simple way.