share PDF file with UIActivityViewController

Related searches

I am trying to share a PDF file using UIActivityViewController but when I press the button I do not have options to share the file How can I show these options ?


import UIKit
import PDFKit
import MessageUI
import UIKit.UIGestureRecognizerSubclass

class BookViewController: UIViewController, UIPopoverPresentationControllerDelegate, PDFViewDelegate, ActionMenuViewControllerDelegate, OutlineViewControllerDelegate, MFMailComposeViewControllerDelegate {

    @IBOutlet weak var btn: UIButton!

    var pdfDocument: PDFDocument?

    @IBOutlet weak var pdfView: PDFView!
    @IBOutlet weak var webview: UIWebView!

    override func viewDidLoad() {

        pdfView.autoScales = true
        pdfView.displayMode = .singlePage
        pdfView.displayDirection = .horizontal
        pdfView.usePageViewController(true, withViewOptions: [UIPageViewControllerOptionInterPageSpacingKey: 20])

        pdfView.document = pdfDocument

        // ActivityViewController

    override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
        coordinator.animate(alongsideTransition: { (context) in
        }, completion: nil)

    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none

    func actionMenuViewControllergmailDocument(_ actionMenuViewController: ActionMenuViewController) {


    func actionMenuViewControllerShareDocument(_ actionMenuViewController: ActionMenuViewController) {


    func actionMenuViewControllerPrintDocument(_ actionMenuViewController: ActionMenuViewController) {


    func outlineViewController(_ outlineViewController: OutlineViewController, didSelectOutlineAt destination: PDFDestination) {
        pdfView.go(to: destination)

    private func resume() {
        let backButton = UIBarButtonItem(image: #imageLiteral(resourceName: "Chevron"), style: .plain, target: self, action: #selector(back(_:)))
        let actionButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(showActionMenu(_:)))
        navigationItem.leftBarButtonItems = [backButton, actionButton]
        pdfView.isHidden = false

    @objc func resume(_ sender: UIBarButtonItem) {

    @objc func back(_ sender: UIBarButtonItem) {
        navigationController?.popViewController(animated: true)

    @objc func showActionMenu(_ sender: UIBarButtonItem) {
        if let viewController = storyboard?.instantiateViewController(withIdentifier: String(describing: ActionMenuViewController.self)) as? ActionMenuViewController {
            let activityVC = UIActivityViewController(activityItems: [self.pdfDocument!], applicationActivities: nil)
            activityVC.popoverPresentationController?.sourceView = self.view

            self.present(activityVC, animated: true, completion: nil)


@IBAction func sharePDF(_ sender: : Any) {

    let fm = FileManager.default

    var pdfURL = (fm.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
    pdfURL = pdfURL.appendingPathComponent("GridLines.pdf") as URL

    //Rename document name to "Hello.pdf"
    let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("Hello.pdf") as NSURL

    do {
        let data = try Data(contentsOf: pdfURL)

        try data.write(to: url as URL)

        let activitycontroller = UIActivityViewController(activityItems: [url], applicationActivities: nil)
        if activitycontroller.responds(to: #selector(getter: activitycontroller.completionWithItemsHandler))
            activitycontroller.completionWithItemsHandler = {(type, isCompleted, items, error) in
                if isCompleted

        activitycontroller.excludedActivityTypes = [UIActivityType.airDrop]
        activitycontroller.popoverPresentationController?.sourceView = self.view
        self.present(activitycontroller, animated: true, completion: nil)

    catch {

Share a PDF with UIActivityViewController in Swift 3 � GitHub, //Save the pdf document to file system. savePdf(). } func savePdf(){. let fileManager = FileManager.default. let paths = ( NSSearchPathForDirectoriesInDomain((. Share a PDF with UIActivityViewController in Swift 3 - sharePDF.swift. Hi the same is not working for the Word file and Excel and Ppt files can you please suggest it is working fine for PDF and Images.

Try like this

let fileManager = FileManager.default 
let docsurl = try! fileManager.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let documentoPath =  docsurl.appendingPathComponent("yourfile.pdf") 

if fileManager.fileExists(atPath: documentoPath){              
   let pdfData = NSData(contentsOfFile: documentoPath) 
    var activityViewController = UIActivityViewController(activityItems: ["Your title that you wanna share", pdfData], applicationActivities: nil)   // and present it
    present(activityViewController, animated: true) {() -> Void in }

Its working fine ... I use it .

UIActivityViewController Tutorial: Sharing Data, My App creates PDF reports and I would like to enable the user to add the PDF to iBooks and send it by email. (Note, the PDF is generated� Sharing is a convenient way for users to send data to each other or between devices. It may even net you some new customers! Fortunately, since iOS 6, Apple has provided the handy, but much-overlooked, UIActivityViewController class, which offers a clean interface for sharing and manipulating data inside your app.

You already have a PDFDocument object, so reconstructing the file url is unnecessary. Simply pass your PDFDocument's documentURL property instead:

let activityVC = UIActivityViewController(activityItems: [self.pdfDocument!.documentURL!], applicationActivities: nil)

Share a PDF (or any file) through UIActivityViewController, In one of my upcoming apps I want the user to be able to send a file using the UIActivityViewController. As I create the NSData object during� This class, UIActivityViewController, can handle sharing text, URLs, image, and more, and is also able to add our app’s own services alongside the others. In this article I'll walk through some complete examples of using UIActivityViewController , partly so you can see what it’s capable of, and partly also so you have one reference guide to

Try with this

let fileManager = FileManager.default 
let docsurl = try! fileManager.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let documentoPath =  docsurl.appendingPathComponent("documento.pdf") 

if fileManager.fileExists(atPath: documentoPath){              
   let documento = NSData(contentsOfFile: documentoPath) 
   let activityViewController: UIActivityViewController = 
   UIActivityViewController(activityItems: [documento!], 
   applicationActivities: nil) 

                present(activityViewController, animated: true, completion: nil) 
            else { 
                print("document was not found") 

UIActivityViewController NSData with Filename –, Share (UIActivity Category Share) activity items share the selected content, such as composing a message containing a URL or posting an image to Twitter. Each activity type supports certain kinds of items. For example, you can post a String, URL, and / or image to Twitter, but you can’t assign a string to be the photo for a contact.

This could include sharing with, Facebook, Email, SMS or any other app that has registered support for the file type. For example PDF readers can handle a PDF, or Facebook and other apps would be able to share image files. Share Dialog. The Share Dialog is native to each platform, and will display differently on each.

Create an instance of UIActivityViewController, set all activity items, including the path of your file you want to share, and the source rectangle the share action was initiated from. iOS

Once we’ve finished drawing each page into the context we’ll end up with an NSData object containing the raw PDF data – this can then be output to a file, and we’re ready to share a PDF. Working with the native share sheet The “share sheet”, known as a UIActivityViewController in the UIKit framework, was introduced in iOS 6.