Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

share pdf file using UIActivityViewController in Swift 4

I am using UIActivityViewController to share a PDF file:

let pdfFilePath = URL(string: "https://www.tutorialspoint.com/swift/swift_tutorial.pdf")
let pdfData = NSData(contentsOf: pdfFilePath!)
let activityVC = UIActivityViewController(activityItems: [pdfData!], applicationActivities: nil)

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

The below result is displayed:

enter image description here

What I want is to display more features like "copy to Books" and "Add to Notes" like the following:

enter image description here

like image 472
Fatima Avatar asked Oct 16 '22 07:10

Fatima


1 Answers

If you want to share your pdf file which is on the server and you have a URL. Then first you download that file in your device and then share that file to any other person.

If you using Alamofire in your code then there is code.

Stape 1

import Alamofire

Stape 2

Add this function in your class:-

func downloadPdf(downloadUrl : String, fileName: String, completionHandler:@escaping(String, Bool)->()){

        let destinationPath: DownloadRequest.DownloadFileDestination = { _, _ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0];
            let fileURL = documentsURL.appendingPathComponent("\(fileName).pdf")
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }
        print(downloadUrl)
        Alamofire.download(downloadUrl, to: destinationPath)
            .downloadProgress { progress in

            }
            .responseData { response in
                print("response: \(response)")
                switch response.result{
                case .success:
                    if response.destinationURL != nil, let filePath = response.destinationURL?.absoluteString {
                        completionHandler(filePath, true)
                    }
                    break
                case .failure:
                    completionHandler("", false)
                    break
                }
        }
    }

Stape 3

Add this action on your share button

@IBAction func btnShareAction(_ sender: UIButton) {

        let myURL = "http://www.demo.com/demo.pdf"  // change this with your URL
        self.downloadPdf(downloadUrl : myURL, fileName: "invoice") { (localFileUrl, bool) in

             let fileURL = NSURL(fileURLWithPath: localFileUrl)
            let activityViewController = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)
            self.present(activityViewController, animated: true, completion: nil)

          }
      }
like image 187
Bijender Singh Shekhawat Avatar answered Oct 20 '22 04:10

Bijender Singh Shekhawat