Open PDF iOS Tutorial
source link: https://www.tuicool.com/articles/hit/fQF3Avn
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
To display an PDF file from inside the app, it can be embedded inside a Web View. In this tutorial we will display a PDF file from the local filesystem onto the screen. This tutorial is made with Xcode 10 and built for iOS 12.
Open Xcode and create a new Single View App.
For product name, use IOSOpenPDFTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.
Go to the Storyboard and add a Button to the Main View. Select the Button and change the title to "Open PDF". Ctrl and drag from the button to the top of the storyboard, hold down the Ctrl key and select the "Top Space to Safe Area" and "Center Horizontally in Safe Area" options.
The Storyboard will look like this.
Select the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl and drag from the Button to the ViewController class and create the following Action
The PDF will be displayed in a WKWebView object. which is part of the WebKit framework, so import it first
import WebKit
A sample pdf is needed sodownload the pdf and add it to the project. Go to the ViewController.swift file and implement the openPDF method.
@IBAction func openPDF(_ sender: Any) { let url = Bundle.main.url(forResource: "Alice_In_Wonderland", withExtension: "pdf") if let url = url { let webView = WKWebView(frame: view.frame) let urlRequest = URLRequest(url: url) webView.load(urlRequest) view.addSubview(webView) } }
The location of the PDF file inside the application's bundle is assigned to the url constant. A web view is created containing the pdf and this web view is added to the main view. Build and Run the project, select the "Open PDF" button, the PDF will be displayed.
You can download the source code of the IOS9OpenPDFTutorial at the ioscreator repository on Github .
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK