sharing text or image with UIActivityViewController in Swift

Swift 3 or later.

Share image in Social media.

 let image: UIImage = arr.blogImage
 let imageToShare = [ image ]
 let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil)
 activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash 
 self.present(activityViewController, animated: true, completion: nil) 

 

Share Text in Social media.

let text = "This is some text that I want to share." // set up activity view controller
let textToShare = [ text ]
let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
// exclude some activity types from the list (optional)
activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ] 
self.present(activityViewController, animated: true, completion: nil) 

 

Share PDF File in Social Media

let fileManager = FileManager.default
let documentoPath = "abc.pdf"
if fileManager.fileExists(atPath: documentoPath!){
  let url = URL(fileURLWithPath: documentoPath)
  let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [url], applicationActivities: nil)
  activityViewController.popoverPresentationController?.sourceView=self.view
  self.present(activityViewController, animated: true, completion: nil)
}else {
   displayAlertWithMessage("Something Went Wrong")
}