Opening a PDF document when clicking a button - ios

I am trying to create an app for my family restaurant in swift. I currently have a button that you click on that takes you too a webviewer page of our menu. I want to make the menu with in the app so it does not redirect to safari.
Basically what I want to do is click a button and it opens the menu pdf within the app instead safari.
The code that I use too open the PDF in a browser:
#IBAction func menu(sender: AnyObject) {
if let url = NSURL(string:"http://nebula.wsimg.com/db5e994c02db104ea89bdf6e59550490?AccessKeyId=895454CA4A1E296ED3E3&disposition=0&alloworigin=1") {
UIApplication.sharedApplication().openURL(url)
}

You can use QLPreviewController to preview your pdf but it needs to be a local resource or downloaded from the web prior to previewing:
Swift 3 or later
import UIKit
import QuickLook
class ViewController: UIViewController, QLPreviewControllerDataSource {
let preview = QLPreviewController()
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return Bundle.main.url(forResource: "menu", withExtension: "pdf")!
as QLPreviewItem
}
override func viewDidLoad() {
super.viewDidLoad()
// set preview data source
preview.dataSource = self
// set current item index (only one = 0)
preview.currentPreviewItemIndex = 0
}
#IBAction func showMenu(sender: UIButton) {
present(preview, animated: true) {
// code
}
}
}

Related

QuickLook/QLPreviewController PDF Text Annotation background becomes black and font becomes small

I am Using QLPreviewController for editing the PDF. Everything is working properly but
if I add text annotation from the QLPreviewController and click on the done button it is working as expected I am getting the URL with edited PDF and if I do other changes for example add image annotation from outside of QLPreviewController and save that pdf using the code
self.pdfDocument.write(to: self.pdfUrl)
and if I open that pdf in the QLPReviewController and tap on the previously added text then the text annotation background becomes Black and the font becomes small.
I have attached the video please check.
**Video Link : ** https://www.dropbox.com/s/m0ql1csr8pars3t/Issue_video.mov?dl=0
I have used the below code for pdf mark up
func openPreview(_ url : URL){
let previewController = QLPreviewController()
previewController.isEditing = true
previewController.delegate = self
self.pdfUrl = url
previewController.dataSource = self
previewController.modalPresentationStyle = .overFullScreen
self.present(previewController, animated: true, completion: nil)
}
extension ViewController : QLPreviewControllerDataSource,QLPreviewControllerDelegate{
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return self.pdfUrl as QLPreviewItem
}
func previewController(_ controller: QLPreviewController, editingModeFor previewItem: QLPreviewItem) -> QLPreviewItemEditingMode {
return .updateContents
}
func previewControllerWillDismiss(_ controller: QLPreviewController) {
}
func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: QLPreviewItem) {
DispatchQueue.main.async {
self.pdfUrl = previewItem.previewItemURL
self.setPDFFile()
self.pdfDocument.write(to: self.pdfUrl)
}
}
}
func setPDFFile(){
if let doc = PDFDocument(url: self.pdfUrl){
self.pdfDocument = doc
self.pdfView.document = doc
}
}

Can we add text, shape and signature in Photo Markup with Pencil Kit?

I am not getting any option to add text, shape and signature while markup a photo with PencelKit in my app. This option is available in Apple's Photos App. I have tried to access this with various properties of CanvasView and PKToolPicker, but with no success.
self.canvasView?.drawing = PKDrawing()
self.canvasView.allowsFingerDrawing = true
if let window = self.view.window, let toolPicker = PKToolPicker.shared(for: window) {
toolPicker.setVisible(true, forFirstResponder: self.canvasView)
toolPicker.addObserver(self.canvasView)
self.canvasView.becomeFirstResponder()
}
I figured it out, finally! It's the QLPreviewController!
Editing with shapes, arrows and signature is only available for iOS13+.
First of all we need to read the file from an url, so set it up with init. I go with something like this as base and append the filename, also with file extension, e.g. .pdf:
FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
You can't save it in the tempDirectory, because the QLPreviewViewController needs access. No permission could result in an error like this:
AX Lookup problem - errorCode:1100 error:Permission denied portName:
Your customVC should look like this:
import UIKit
import QuickLook
class CustomVC: UIViewController {
var url: URL
init(url: URL) {
self.url = url
}
....func viewDidLoad() and stuff ......
func editFile() {
let editor = QLPreviewController()
editor.dataSource = self
editor.delegate = self
editor.setEditing(true, animated: true)
present(editor, animated: true, completion: nil)
}
}
// Load the file in the QLPreviewController with DataSource
extension CustomVC: QLPreviewControllerDataSource {
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return self.url! as QLPreviewItem
}
}
// Make editing available with Delegate
#available(iOS 13.0, *)
extension CustomVC: QLPreviewControllerDelegate {
func previewController(_ controller: QLPreviewController, editingModeFor previewItem: QLPreviewItem) -> QLPreviewItemEditingMode {
return .updateContents
}
func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: QLPreviewItem) {
print("UPDATE")
}
func previewController(_ controller: QLPreviewController, didSaveEditedCopyOf previewItem: QLPreviewItem, at modifiedContentsURL: URL) {
print("SAVED at \(modifiedContentsURL)")
}
}
The markup button will show automatically if you have implemented these functions in the delegate correctly.
You can also add more barButtonItems for this VC like normal with an extra navigationController, e.g. something like this in the editFile function:
let navController = UINavigationController(rootViewController: editor)
let customButton = UIBarButtonItem(image: UIImage(systemName: "yourImageName"), style: .plain, target: self, action: #selector(customButtonTapped(_:)))
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonTapped(_:)))
if var items = editor.navigationItem.rightBarButtonItems {
items.append(customButton)
editor.navigationItem.rightBarButtonItems = items
} else {
editor.navigationItem.rightBarButtonItems = [customButton]
}
editor.navigationItem.leftBarButtonItem = doneButton
viewController?.present(navController, animated: true, completion: nil)
self.navigationController = navController

Hide or disable share button from uidocumentinteractioncontroller in swift 5

In my application, I'm using the QuickLook framework to view the document files such as pdf, ppt, doc, etc. etc. But due to privacy concerns, I don't want that the user can share this document with others so please let me know how to disable/hide the share button and also the copy-paste option.
I know this question can be asked by a number of times and tried many solutions but nothing works for me
hide share button from QLPreviewController
UIDocumentInteractionController remove Actions Menu
How to hide share button in QLPreviewController using swift?
Hide right button n QLPreviewController?
Please suggest to me to achieve this.
Here is my demo code:
import UIKit
import QuickLook
class ViewController: UIViewController {
lazy var previewItem = NSURL()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func displayLocalFile(_ sender: UIButton){
let previewController = QLPreviewController()
// Set the preview item to display
self.previewItem = self.getPreviewItem(withName: "samplePDf.pdf")
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)
}
#IBAction func displayFileFromUrl(_ sender: UIButton){
// Download file
self.downloadfile(completion: {(success, fileLocationURL) in
if success {
// Set the preview item to display======
self.previewItem = fileLocationURL! as NSURL
// Display file
let previewController = QLPreviewController()
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)
}else{
debugPrint("File can't be downloaded")
}
})
}
func getPreviewItem(withName name: String) -> NSURL{
// Code to diplay file from the app bundle
let file = name.components(separatedBy: ".")
let path = Bundle.main.path(forResource: file.first!, ofType: file.last!)
let url = NSURL(fileURLWithPath: path!)
return url
}
func downloadfile(completion: #escaping (_ success: Bool,_ fileLocation: URL?) -> Void){
let itemUrl = URL(string: "https://images.apple.com/environment/pdf/Apple_Environmental_Responsibility_Report_2017.pdf")
// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent("filename.pdf")
// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
debugPrint("The file already exists at path")
completion(true, destinationUrl)
// if the file doesn't exist
} else {
// you can use NSURLSession.sharedSession to download the data asynchronously
URLSession.shared.downloadTask(with: itemUrl!, completionHandler: { (location, response, error) -> Void in
guard let tempLocation = location, error == nil else { return }
do {
// after downloading your file you need to move it to your destination url
try FileManager.default.moveItem(at: tempLocation, to: destinationUrl)
print("File moved to documents folder")
completion(true, destinationUrl)
} catch let error as NSError {
print(error.localizedDescription)
completion(false, nil)
}
}).resume()
}
}
}
//MARK:- QLPreviewController Datasource
extension ViewController: QLPreviewControllerDataSource {
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
controller.navigationItem.rightBarButtonItem = nil
return self.previewItem as QLPreviewItem
}
}
Please provide your suggestion to do so or any other framework to view different file formats.
Here is the image
Find below adopted my approach to your code (with modifications to test locally, but the code should be clear). The idea is
a) to override, which is completely allowed by API, needed classes to intercept modification
b) to use intentionally own UINavigationController, as only one navigation controller can be in stack
So here is code:
// Custom navigation item that just blocks adding right items
class MyUINavigationItem: UINavigationItem {
override func setRightBarButtonItems(_ items: [UIBarButtonItem]?, animated: Bool) {
// forbidden to add anything to right
}
}
// custom preview controller that provides own navigation item
class MyQLPreviewController: QLPreviewController {
private let item = MyUINavigationItem(title: "")
override var navigationItem: UINavigationItem {
get { return item }
}
}
class MyViewController : UIViewController, QLPreviewControllerDataSource {
lazy var previewItem = NSURL()
override func loadView() {
let view = UIView()
view.backgroundColor = .white
// just stub testing code
let button = UIButton(type: .roundedRect)
button.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
button.setTitle("Show", for: .normal)
button.addTarget(self, action:
#selector(displayLocalFile(_:)), for: .touchDown)
view.addSubview(button)
self.view = view
}
#objc func displayLocalFile(_ sender: UIButton){
let previewController = MyQLPreviewController() // << custom preview
// now navigation item is fully customizable
previewController.navigationItem.title = "samplePDF.pdf"
previewController.navigationItem.leftBarButtonItem =
UIBarButtonItem(barButtonSystemItem: .done, target: self,
action: #selector(closePreview(_:)))
// wrap it into navigation controller
let navigationController = UINavigationController(rootViewController: previewController)
// Set the preview item to display
self.previewItem = self.getPreviewItem(withName: "samplePDF.pdf")
previewController.dataSource = self
// present navigation controller with preview
self.present(navigationController, animated: true, completion: nil)
}
#objc func closePreview(_ sender: Any?) {
self.dismiss(animated: true) // << dismiss preview
}
func getPreviewItem(withName name: String) -> NSURL{
// Code to diplay file from the app bundle
let file = name.components(separatedBy: ".")
let path = Bundle(for: type(of: self)).path(forResource: file.first!, ofType: file.last!)
let url = NSURL(fileURLWithPath: path!)
return url
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return self.previewItem as QLPreviewItem
}
}

Display PDF file in Swift 4

import UIKit
import WebKit
class ViewController: UIViewController, UIDocumentInteractionControllerDelegate {
var docController: UIDocumentInteractionController!
override func viewDidLoad() {
super.viewDidLoad()
docController = UIDocumentInteractionController.init(url: URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(urlVal!))
docController.delegate = self
docController.presentPreview(animated: true)
}
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
}
Above code I'm not able to display the pdf file. Can anyone help?
By seeing your code it seems that you missed to add UIDocumentInteractionControllerDelegate delegate method.
class ViewController: UIViewController,UIDocumentInteractionControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
var docController = UIDocumentInteractionController.init(url: URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(urlVal!))
docController.delegate = self
docController.presentPreview(animated: true)
}
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
}
OR
You can also view PDF by loading it into WKWebView.
override func viewDidLoad() {
super.viewDidLoad()
let pdfFilePath = Bundle.main.url(forResource: "iostutorial", withExtension: "pdf")
let urlRequest = URLRequest.init(url: pdfFilePath!)
webView = WKWebView(frame: self.view.frame)
webView.load(request)
self.view.addSubview(webView)
}
Basically you are missing the UIDocumentInteractionControllerDelegate implementation. For preview, you should implement this method
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController
Return which ViewController need to display the Preview. If you pass the self View Controller it will display the PDF preview in the existing view controller modally. Just do this one in your View controller if you want to display the preview in the same controller.
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
If you are already doing this in your code, there is high chance of PDF URL path might be wrong.
I would use the Quicklook framework instead, it supports a wide range of document types:
iWork documents
Microsoft Office documents
PDF files
Images
Text files
Rich-Text Format documents
Comma-Separated Value files (csv)
Supports sharing of the relevant documents as well and is easy to implement.
Follow this tutorial on how to do it in Swift: https://www.appcoda.com/quick-look-framework/
Swift 5
Import this framework
import SafariServices
Then call this sentences whenever you need
if let url = URL(string: "YOUR_PDF_URL") {
let config = SFSafariViewController.Configuration()
config.entersReaderIfAvailable = true
let vc = SFSafariViewController(url: url, configuration: config)
present(vc, animated: true)
}
The code will present a Safari view with the pdf on it.

How to display pdf from network in iOS [duplicate]

This question already has answers here:
How to display remote document using QLPreviewController in swift
(2 answers)
Closed 5 years ago.
Currently I am using QuickLook module to open pdf from network, but it shows a blank page with error "Couldn't issue file extension for url: https://testing-xamidea.s3.amazonaws.com/flowchart/20171103182728150973368.pdf" in console. I guess QuickLook can only open locally saved Pdf files. Is is possible to load pdf from network using quicklook? . This is my code so far- {fileURL contains url from which pdf is to be loaded, also ive set the delegates etc)
extension FlowchartVC:QLPreviewControllerDelegate,QLPreviewControllerDataSource {
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
let url : NSURL! = NSURL(string : fileURL)
return url
}
func previewControllerWillDismiss(_ controller: QLPreviewController) {
self.dismiss(animated: true, completion: nil)
}
}
You need to save the file to disk first and then you can present the pdf. There is no way to present it with QuickLook if the file is in a remote location. The file is saved in the temporary directory. Here is an example view controller showing how it could be done.
Swift 5:
import UIKit
import QuickLook
class ViewController: UIViewController, QLPreviewControllerDataSource {
// Remote url pdf I found on google
let itemURL = URL(string: "https://www.ets.org/Media/Tests/GRE/pdf/gre_research_validity_data.pdf")!
var fileURL: URL?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let quickLookController = QLPreviewController()
quickLookController.dataSource = self
do {
// Download the pdf and get it as data
// This should probably be done in the background so we don't
// freeze the app. Done inline here for simplicity
let data = try Data(contentsOf: itemURL)
// Give the file a name and append it to the file path
fileURL = FileManager().temporaryDirectory.appendingPathComponent("sample.pdf")
if let fileUrl = fileURL {
// Write the pdf to disk in the temp directory
try data.write(to: fileUrl, options: .atomic)
}
// Make sure the file can be opened and then present the pdf
if QLPreviewController.canPreview(fileUrl as QLPreviewItem) {
quickLookController.currentPreviewItemIndex = 0
present(quickLookController, animated: true, completion: nil)
}
} catch {
// cant find the url resource
}
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return fileURL! as QLPreviewItem
}
}
Swift 3:
import UIKit
import QuickLook
class ViewController: UIViewController, QLPreviewControllerDataSource {
// Remote url pdf I found on google
let itemURL = URL(string: "https://www.ets.org/Media/Tests/GRE/pdf/gre_research_validity_data.pdf")!
var fileURL = URL(string: "")
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let quickLookController = QLPreviewController()
quickLookController.dataSource = self
do {
// Download the pdf and get it as data
// This should probably be done in the background so we don't
// freeze the app. Done inline here for simplicity
let data = Data(contentsOf: itemURL)
// Give the file a name and append it to the file path
fileURL = FileManager().temporaryDirectory.appendingPathComponent("sample.pdf")
// Write the pdf to disk
try data?.write(to: fileURL!, options: .atomic)
// Make sure the file can be opened and then present the pdf
if QLPreviewController.canPreview(fileUrl as QLPreviewItem) {
quickLookController.currentPreviewItemIndex = 0
present(quickLookController, animated: true, completion: nil)
}
} catch {
// cant find the url resource
}
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return fileURL! as QLPreviewItem
}
}
Here is the file showing in the simulator. Using a sample project with just that code.

Resources