Skip to content

Instantly share code, notes, and snippets.

@ifsamaed
Created June 27, 2017 08:30
Show Gist options
  • Select an option

  • Save ifsamaed/147f8f4237ad76fecb17d96fdd8b4db0 to your computer and use it in GitHub Desktop.

Select an option

Save ifsamaed/147f8f4237ad76fecb17d96fdd8b4db0 to your computer and use it in GitHub Desktop.
Share a PDF with UIActivityViewController in Swift 3
class yourViewController: UIViewController{
var documentPathToLoad = "http://youPdfFile.pdf"
func webViewDidFinishLoad(_ webView: UIWebView) {
if yourWebView.isLoading {
// still loading
return
}
//Save the pdf document to file system
savePdf()
}
func savePdf(){
let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomain((.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("documento.pdf")
let pdfDoc = NSData(contentsOf:URL(string: documentPathToLoad)!)
fileManager.createFile(atPath: paths as String, contents: pdfDoc as Data?, attributes: nil)
}
}
func loadPDFAndShare(){
let fileManager = FileManager.default
let documentoPath = (self.getDirectoryPath() as NSString).appendingPathComponent("documento.pdf")
if fileManager.fileExists(atPath: documentoPath){
let documento = NSData(contentsOfFile: documentoPath)
let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [documento!], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView=self.view
present(activityViewController, animated: true, completion: nil)
}
else {
print("document was not found")
}
}
@surya25ios

Copy link
Copy Markdown

Hey, good job.Can you please provide the getDirectoryPath() method ,please.Many Thanks

@tetwegsd

tetwegsd commented Sep 1, 2018

Copy link
Copy Markdown

func getDirectoryPath() -> String { let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentsDirectory = paths[0] return documentsDirectory }

@rajendra561

Copy link
Copy Markdown

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.

This is the sample Word file I used

https://www.fda.gov/downloads/aboutfda/aboutthiswebsite/.../ucm261370.doc

@ahmedAsoliman

Copy link
Copy Markdown

it is not working with me
just send text
no files

@User2004

Copy link
Copy Markdown

@Luzo

Luzo commented Oct 11, 2019

Copy link
Copy Markdown

I guess you will have problems with other file types other than PDF due to saving everything as "documento.pdf".

@shahsaumil2001

Copy link
Copy Markdown

Is it possible to share audio mp3 file and audio notes at the same time?

@AD-Paladins

Copy link
Copy Markdown

Gist to store base64 string PDF, get from directory and share it
https://gist.github.com/titopalito/6a273b6c8880140804b655a4e23187c7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment