How to open and close a PDF file using Swift?

iOSiPhone/iPadMobile Development

In this article we’ll see how to open a pdf file using swift in iOS. Here we’ll do it with an example of opening pdf in webView in iOS. Let’s create a project and add WKWebView to the storyboard.

Connect it’s outlet to the ViewController class.

Now we’ll see two different things

  • Opening a PDF file from a URL on the web.

To open a web view from a url, first we need to have a url with a pdf file. In this example I’ll be using a dummy URL

Let’s create a URL first,

let url: URL! = URL(string: "")

Now the remaining steps are similar in both the methods, so let’s see method 2 and remaining steps.

  • Opening a PDF from local storage.

if let pdfURL = Bundle.main.url(forResource: "dummy", withExtension: "pdf", subdirectory: nil, localization: nil) {
   let request = URLRequest.init(url: pdfURL)

In the first line we created a URL, and then step two and step three are to create a request and load in the web View.

When we run any of the methods above in simulator we get the result similar to shown below.

Updated on 30-Jul-2019 22:30:24