Tutorials

How to Build iOS PDF Viewer with SwiftUI

By ComPDFKit | Fri. 09 Aug. 2024
iOSSwift

 

Build iOS PDF Viewer with SwiftUI

 

 

SwiftUI is Apple's latest user interface framework, designed to revolutionize the way developers create UI for iOS, macOS, watchOS, and tvOS. Launched at WWDC 2019, SwiftUI offers a modern, declarative syntax that allows developers to build complex UIs with less code and a more intuitive development process.

 

It is widely used for Apple apps, including PDF applications. In this article, you’ll see the Swift tutorial example and learn how to build a SwiftUI PDF viewer with ComPDFKit iOS PDF Library.

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free

 

 

Step 1: Requirements for Swift UI PDF Library Integration

 

To integrate the ComPDFKit iOS PDF library through SwiftUI, the following requirements are needed.

 

 

Note: ComPDFKit requires the latest stable version of Xcode available at the time the release was made. This is a hard requirement, as each version of Xcode is bundled with a specific version of the iOS Base SDK, which often defines how UIKit and various other frameworks behave.

 

 

Step 2: Get iOS Library Package for Your SwiftUI PDF Viewer

 

To follow the SwiftUI tutorial example in Swift, it's essential to download the ComPDFKit iOS PDF Library in Swift. This library will enable you to seamlessly integrate PDF viewing capabilities into your SwiftUI application.

 

 

SDK Package of ComPDFKit for iOS

 

 

Step 3: Get Trial License for ComPDFKit PDF Library

 

Easily obtain a ComPDFKit iOS Library 30-day license with just a few clicks on the ComPDFKit website. No sales involved. Simply apply for the appropriate license, and you'll receive an email with the license automatically. Integrate the Swift PDF library into your project seamlessly.

 

Get License for iOS PDF SDK of ComPDFKit

 

 

Step 4: Apply the License Key for Your Swift UI PDF APP

 

Find the License Key

Here are the step tutorials for you to find the correct License Key to integrate PDF Viewer library into your SwiftUI project.

 

  1. In the email you received, locate the XML file containing the license key.

  2. Open the XML file and determine the license type through the <type>online</type> field. If present, it is an online license; if absent or <type>offline</type> is present, it is an offline license.

     

     

    Online License:

    xmlCopy code
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <license version="1">
        <platform>ios</platform>
        <starttime>xxxxxxxx</starttime>
        <endtime>xxxxxxxx</endtime>
        <type>online</type>
        <key>LICENSE_KEY</key>
    </license>

     

    Offline License:

    xmlCopy code
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <license version="1">
        <platform>ios</platform>
        <starttime>xxxxxxxx</starttime>
        <endtime>xxxxxxxx</endtime>
        <key>LICENSE_KEY</key>
    </license>
  3. Copy the LICENSE_KEY from the <key>LICENSE_KEY</key> field.

 

Apply the License Key

Go to the ComPDFKit official website's Online Sales Interface to submit a trial application and receive an immediate free trial license for iOS platforms, valid for 30 days. Before using any ComPDFKit PDF SDK classes, you must perform the following steps to apply the license to your application:

 

  1. In AppDelegate.swift, import the header file ComPDFKit.

  2. Depending on the type of authentication obtained in the previous step, whether online or offline, initialize the license using the respective method based on your requirements.

  3. Initialize the license:

 

    • Online license:

Follow the code below and call the method CPDFKit.verify(withOnlineLicense: "LICENSE_KEY") { code, message in } in func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool. You need to replace the LICENSE_KEY with the license you obtained.

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  // Set your online license key here. ComPDFKit is commercial software.
  // Each ComPDFKit license is bound to a specific app bundle id.
  // com.compdfkit.pdfviewe
    
    CPDFKit.verify(withOnlineLicense: "YOUR_LICENSE_KEY_GOES_HERE") { code, message in
    }
}

 

    • Offline license:

Follow the code below and call the method CPDFKit.verifyWithKey:"LICENSE_SECRET" in func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool. You need to replace the LICENSE_KEY with the license you obtained.

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  // Set your license key here. ComPDFKit is commercial software.
  // Each ComPDFKit license is bound to a specific app bundle id.
  // com.compdfkit.pdfviewer
    
    CPDFKit.verify(withKey: "YOUR_LICENSE_KEY_GOES_HERE")
    return true
}

 

 

Step 5: Integrate ComPDFKit iOS PDF Library — SwiftUI Tutorials

 

Let's discuss how to integrate ComPDFKit for iOS in SwiftUI framework and build an iOS PDF Viewer to display a PDF.

 

1. Bridge CPDFViewController to SwiftUI

First, declare the CPDFSwiftViewController structure — which conforms to the UIViewControllerRepresentable protocol — so that you can bridge from UIKit to SwiftUI. After that, add a property of type CPDFConfiguration and implement the protocols as seen below:

import ComPDFKit

struct CPDFSwiftViewController: UIViewControllerRepresentable {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    class Coordinator: NSObject,CPDFViewBaseControllerDelete {
        var myview: CPDFSwiftViewController
        init(_ myview: CPDFSwiftViewController) {
            self.myview = myview
        }
        
        // MARK: - CPDFViewBaseControllerDelete
        func PDFViewBaseControllerDissmiss(_ baseControllerDelete: CPDFViewBaseController) {
            baseControllerDelete.dismiss(animated: true)
        }
            
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    func makeUIViewController(context: Context) -> CNavigationController {
        CPDFKit.verify(withKey: "LICENSE_KEY")
      
        let filePath = Bundle.main.path(forResource: "developer_guide_ios", ofType: "pdf")  ?? ""
        
        let configuration = CPDFConfiguration()
 
        let vc = CPDFViewController(filePath: filePath, password: nil, configuration: configuration)
        vc.delegate = context.coordinator;
        let navController = CNavigationController(rootViewController: vc)
        navController.modalPresentationStyle = .fullScreen

        return navController
    }
    
    func updateUIViewController(_ uiViewController: CNavigationController, context: UIViewControllerRepresentableContext<CPDFSwiftViewController>) {
        
    }

}

 

2. Use ComPDFKitView in SwiftUI

Use CPDFViewController in your SwiftUI content view:

struct ContentView: View {
    @State var isPresented: Bool = false

    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")
            
            .toolbar {

                ToolbarItem(placement: .bottomBar) {
                    Button("Click to open the sample PDF") {
                        isPresented = true
                    }
                }
            }
            .fullScreenCover(isPresented: $isPresented) {
                CPDFSwiftViewController()

            }
        }
        .padding()
    }
}

 

In this guide, we use an iPad 14 device as an example. After building the demo successfully, the "developer_guide_ios.pdf" file will be opened and displayed.

 

iOS pdf sdk demo of ComPDFKit

 

ComPDFKit boasts a highly skilled R&D team dedicated to providing extensive technical documentation and guides, essential for developers. For an efficient and feature-rich SwiftUI PDF apps, ComPDFKit is your go-to solution.

 

  • Detailed Information: Explore our Guides for comprehensive insights.

  • Latest Updates: Check out our Changelog for the newest enhancements.

  • Technical Assistance: Get prompt support from our Technical Support team.

  • Accurate Quotes: Reach out to our Sales Team for detailed inquiries and quotes.

 

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free

 

 

FAQ about SwiftUI & ComPDFKit

 

1. How to Get SwiftUI Updates?

What's new in SwiftUI - WWDC24: SwiftUI has introduced numerous new APIs, making it more convenient to work with the framework. This includes enhancements to core components, new ways to use foundational APIs, and ease of use improvements. You can now create custom container views.

 

2. What is UIKit and SwiftUI?

SwiftUI and UIKit are frameworks for designing user interfaces in iOS development. SwiftUI offers a modern, streamlined approach to UI development, while UIKit provides robustness and versatility.

 

3. What is the difference between Swift and SwiftUI?

  • Swift is a programming language created by Apple Inc. It is a powerful and fast language that makes development on Apple products more enjoyable and efficient.
  • SwiftUI is a declarative framework for building user interfaces on Apple platforms.

 

4. Why is SwiftUI better?

SwiftUI excels in quicker UI development, a declarative syntax for control, Swift integration, and cross-platform compatibility. The framework offers a rich set of transitions and animations, enhancing the user experience.

 

5. What are the disadvantages of SwiftUI?

  • Limited Deployment: SwiftUI is supported only on iOS 13+, macOS 10.15+, watchOS 6+, and tvOS 13+.
  • Maturation Stage: As a newer framework, SwiftUI is still evolving and maturing.

 

6. Why ComPDFKit PDF SDK for iOS?

ComPDFKit PDF SDK for iOS is designed to make PDF handling seamless and efficient. It offers robust features for viewing, annotating, editing, and converting PDF files. Its high performance and flexibility make it an excellent choice for developers looking to integrate PDF functionalities into their iOS applications.

 

7. Where can I find all ComPDFKit iOS PDF library developer guides?

All developer guides can be found on the documentation page.

 

8. Where can I download the ComPDFKit PDF libraries?

Download on GitHub.

 

9. Where can I get the trial license of ComPDFKit for iOS?

The license can be obtained on the pricing page directly (Without sales).

 

10. How long can I trial ComPDFKit for iOS for free?

You can integrate ComPDFKit for iOS for 30 days. If you need more days for your free trial, you can contact the sales team.

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free