With Xcode 6, Apple introduced a brand new programming language, Swift. PDFNet is easy to use with a Swift project. This post will show how to set up a new Swift project and display a PDF.
This post will show you the basics of starting a new Swift project that uses PDFNet. For a comprehensive introduction to PDFNet on iOS, please see Getting Started on iOS. A completed Swift sample project is included with the most recent version of PDFNet for iOS.
1. Open Xcode 6.0.1+, and select File->New Project->Single View Application. Create a new Universal Swift app.
2. Add the following PDFNet files to your project:
- Lib/PDFNet.framework
- Lib/libTools.a
- Lib/pdfnet.res
- Lib/NSObjectInitWithCptr.h
- Lib/NSObjectInitWithCptr.m
- Lib/src/PDFViewCtrlTools/Tools/ToolManager.h
- Lib/src/PDFViewCtrlTools/Tools/PanTool.h
- Lib/src/PDFViewCtrlTools/Tools/Loupe.png
- Lib/src/PDFViewCtrlTools/Tools/Loupe@2x.png
- TestFiles/mech.pdf
3. Link in the following Apple frameworks
- MediaPlayer.framework
- CoreText.framework
- CoreMedia.framework
4. Change the extension of Lib/NSObjectInitWithCptr.m to .mm (so that the C++ library will be linked in).
5. Add a new header called BridgingHeader.h and change its contents to the following:
#ifndef SwiftSample_BridgingHeader_h #define SwiftSample_BridgingHeader_h #import <PDFNet/PDFViewCtrl.h> #import <PDFNet/PDFNetOBJC.h> #import "PanTool.h" #import "ToolManager.h" #endif
6. Identify the bridging header as such in the project settings. In the Swift Compiler – Code Generation section, set Objective-C Binding Header to the path to BridgingHeader,h.
7. In the file ViewController.swift, change the viewDidLoad() function to the following:
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // initialize PDFNet PTPDFNet.Initialize("") // set the resource file let resourceFilePath = NSBundle.mainBundle().pathForResource("pdfnet", ofType: "res") PTPDFNet.SetResourcesPath(resourceFilePath!) // create a PTPDFViewCtrl and add it to the view let ctrl = PTPDFViewCtrl() ctrl.frame = CGRect(origin: CGPointZero, size: self.view.bounds.size) ctrl.SetBackgroundColor(180, g: 180, b: 180, a: 255) self.view.addSubview(ctrl) // open the PDF document included in the bundle in the PTPDFViewCtrl let docPath = NSBundle.mainBundle().pathForResource("mech", ofType: "pdf") let doc = PTPDFDoc(filepath: docPath!) ctrl.SetDoc(doc) // add the toolmanager (used to implement text selection, annotation editing, etc. let toolManager = ToolManager(PDFViewCtrl: ctrl) ctrl.toolDelegate = toolManager; toolManager.changeTool(PanTool) }
If you run the project, the program should now display the PDF mech.pdf. As stated above, a completed version of this sample is available in the latest version of PDFNet, so please check it out!
