How to Build an iOS PDF Viewer or Editor in Swift

Tutorials | Swift · Integration · PDF Viewer · iOS Fri. 28 Apr. 2023

In today's mobile-first world, creating an iOS app is a must-have for businesses and developers alike. And, with the increasing need to work with PDF documents, building an iOS PDF viewer and editor with ComPDFKit, a powerful PDF SDK, enable your end users to view and edit PDFs with ease.

 

In this blog, we'll start by exploring the necessary steps to integrate the ComPDFKit PDF SDK and build an iOS PDF Reader with ComPDFKit.

 

 

Get Started with ComPDFKit iOS PDF SDK

 

ComPDFKit is a powerful PDF SDK. It is easy to embed ComPDFKit PDF SDK in your iOS application with a few lines of Swift code. Take just a few minutes and get started.

 

The following sections introduce the requirements, structure of the installation package, and how to make an iOS PDF Reader in Swift with ComPDFKit PDF SDK.

 

Requirements

 

The following developing environment is required to develop programs with ComPDFKit PDF SDK. ComPDFKit PDF SDK may not work when your developing environment is lower.

 

         - Device System: iOS 10.0 or higher.

         - IDE Version: Xcode 12.0 or newer. We take Xcode 14.0.1 as an example in this blog.

IDE Version

 

         - Currently, running on Apple Silicon emulator is not supported on Mac’s M series chips.

 

For earlier versions of Xcode (Like Xcode 13), the Bitcode option might be turned on by default, which requires it to be turned off to run. The precise steps to do this are illustrated in the figure below:

 

Bitcode option

 

iOS Package Structure

 

You can contact us to access our PDF SDK installation package. Download and decompress the package of ComPDFKit PDF SDK for iOS. You will see all the following files in the SDK package.

 

         - ComPDFKit.xcframework - Include the ComPDFKit dynamic library (arm64_armv7, x86_64-simulator) and associated header files.

         - PDFViewer - A folder containing (Objective-C) iOS sample projects.

         - PDFViewer-Swift - A folder containing (Swift) iOS sample projects.

         - api_reference_ios - API reference.

         - developer_guide_ios.pdf - Developer guide.

         - release_notes.txt - Release information.

         - legal.txt - Legal and copyright information.

 

iOS Package Structure

 

 

Make an iOS PDF Viewer in Swift

 

This section will help you to quickly get started with ComPDFKit PDF SDK to make an iOS app in Swift with step-by-step instructions. Through the following steps, you will get a simple application that can display the contents of a specified PDF file. We take Xcode 14.0.1 as an example in this blog.

 

Step 1: Create a New Project

 

1. Fire up Xcode, and choose File-> New -> Project. Then, select App in iOS -> Application. And then, click Next.

 

Create a New Project 1

 

2. Choose the options for your new project:

         - Enter the name of your product, for example, PDFViewer.

         - Choose and enter the Apple developer account of the app you want to release.

         - Enter the name of your organization identifier (com.example.pdfviewer).

         - Choose Storyboard for the interface.

         - Choose the programming Language "Swift".

         - Click the Next button.

         - Place the project to the location as desired. Then, click Create.

 

Create a New Project 2

 

Step 2: Add ComPDFKit PDF SDK Package

 

1. Find the ComPDFKit.xcframework in the ComPDFKit PDF SDK package. It includes all binary files for architectures.

 

2. Open the newly created iOS project and select General in the panel on the right. Then locate the section of Frameworks, Libraries, and Embedded Content, and drag the ComPDFKit.xcframework directly into this section, and set the Embed option to Embed & Sign.

 

3. Use the shortcut "Command_B" to build the project. If there is no errors reported, it means the configuration is correct and you can proceed to the next step. If some errors are reported, you need to check the reason for the errors. If you cannot identify the errors, you can contact our technical team to solve the issues.

 

Add ComPDFKit PDF SDK Package

 

Step 3: Import Objective-C into Swift

 

Because the ComPDFKit PDF SDK for iOS was developed based on Objective-C, it is compatible with Swift projects. Therefore, in Swift projects, you need to import both the ComPDFKit.xcframework and the header files. There are two ways provided to import the SDK in Swift projects:

 

1. The First Method: Header file bridging. If you do not know how to create bridging files in Swift projects, you can find the answer here.

 

Import Objective-C into Swift 1

 

2. The Second Method: Import modules. Find the ComPDFKit.xcframework folder -> ios-arm64_armv7 -> ComPDFKit.framework -> Modules. Then, import the Modules folder entirely or just import the Module files within the Modules folder. See the picture below for the details.

 

Import Objective-C into Swift 2

 

Step 4: Apply the License Key

 

1. Import the header file ComPDFKit/ComPDFKit.h to AppDelegate.

 

2. Follow the code below and call the method CPDFKit.setLicenseKey("LICENSE_KEY", secret:"LICENSE_SECRET") in didFinishLaunchingWithOptions. You need to replace the LICENSE_KEY and LICENSE_SECRET with the license you obtained.

 

 CPDFKit.setLicenseKey("LICENSE_KEY", secret: "LICENSE_SECRET")

 

Compile and run the project. If the console outputs "version information", it means that the License has been set successfully. Otherwise, please check the "Troubleshooting" section at the end of this blog or check error logs in the console to quickly identify and solve the issue.

 

Step 5: Display a PDF Document

 

1. Prepare a test PDF file, drag and drop it into the newly created pdfView project. By this way, you can load and preview the local PDF document using NSBundle. The following image shows an example of importing a PDF document named “Online5" into the project.

 

Display a PDF Document 1

 

2. Create a CPDFDocument object through URL, and create a CPDFView to display it. The following code shows how to load PDF data using a local PDF path and display it by CPDFView.

​ 

   let document = CPDFDocument(url: url)
        
   if let error = document?.error, error._code != CPDFDocumentPasswordError {
      return
   }  
   let pdfView = CPDFView(frame: view.bounds)  
   pdfView.document = document

 

3. Add the created CPDFView to the view of the current controller. Sample code shows below.

   view.addSubview(pdfView)

 

4. Connect your device or simulator, and use shortcut "Command_R" to run the App. The PDF file will be opened and displayed.

 

Run the App

 

5. If the PDF content cannot be displayed, check if the created NSURL and CPDFDocument objects are empty, or if the size of the created CPDFView is zero. They should not be empty.

 

If there are special characters in the file path, your NSURL will be nil. Handle it with the following code.

 

  filePath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

 

If the size of the created CPDFView is zero, follow the code below to adjust the size of View.

   pdfView.frame = self.view.bounds

 

All the code to create a CPDFViewController shows below:

import UIKit
import ComPDFKit
class ViewController: UIViewController {
    
    public var filePath: String = String()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let url = URL(filePath: filePath)
//        let url = URL(fileURLWithPath: fliePath)
        let document = CPDFDocument(url: url)
        
        if let error = document?.error, error._code != CPDFDocumentPasswordError {
            return
        }
        
        let pdfView = CPDFView(frame: view.bounds)
        pdfView.document = document
        view.addSubview(pdfView)
    }
}

 

SceneDelegate sample code:

import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
    {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        
        let fileURL = Bundle.main.bundleURL.appendingPathComponent("xxxx.pdf")
//        let writbaleURL = copyFileURLToDocumentFolder(fileURL)
        let writbaleURL = fileURL.path()
        
        let tPDFViewController:ViewController = ViewController.init()
        tPDFViewController.fliePath = writbaleURL
        
        window!.rootViewController = UINavigationController(rootViewController: tPDFViewController)
        window!.makeKeyAndVisible()
        guard let _ = (scene as? UIWindowScene) else { return }
    }
    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
    }
    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }
    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }
    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }
    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }
}

​ 

Note: We display a PDF with the iPhone 14 Pro iOS16.2 simulator in this sample code.

 

 

Troubleshooting

 

1. Bitcode

Even when all configurations are correct, there may still be compilation errors. First, check if bitcode is disabled. In older versions of Xcode (such as Xcode 13), the Bitcode option may be enabled by default. It needs to be set to No in order to run the app.

 

2. License

If a License setting error occurs, ensure that the Identity (Bundle ID) setting in General matches the Bundle ID you provided when contacting us for the license. If an expired License message appears, please contact the ComPDFKit team to obtain the latest License and Key.

 

3. No PDF Displayed

Check if the special encoding is required in the path we passed in, or if the local path we passed in exists.

 

4. Other Problems

If you meet some other problems when integrating our ComPDFKit PDF SDK for iOS, feel free to contact ComPDFKit team.

Ready to Get Started?

Download our all-in-one ComPDFKit for free and run it to your project within minutes!