Sharing text and Url to Facebook Messenger with UIActivityViewController but failing - ios

I want to share both text and url to Facebook Messenger using UIActivityViewController.
But when i success send and open my Messenger, i only get url.
Is it possible send text and url to Facebook Messenger using UIActivityViewController at the same time?
Here is my code
#IBAction func sharedLink(_ sender: Any) {
let url = NSURL(string: "https://www.google.com.tw")!
let text = "test" as AnyObject
let shareObject: [AnyObject] = [text, url as AnyObject]
let vc = UIActivityViewController(activityItems: shareObject, applicationActivities: [])
vc.completionWithItemsHandler = { (type,completed,items,error) in
if completed { vc.dismiss(animated: true, completion: nil) }
}
present(vc, animated: true, completion: nil)
}
Here is my screenshot

In my case,
#IBAction func sharedLink(_ sender: Any) {
let urlString = "https://www.google.com.tw"
let url = NSURL(string: urlString)!
let text = "test" as AnyObject
let shareObject: [AnyObject] = ["\(text), \(urlString)"]
let vc = UIActivityViewController(activityItems: shareObject, applicationActivities: [])
vc.completionWithItemsHandler = { (type,completed,items,error) in
if completed { vc.dismiss(animated: true, completion: nil) }
}
present(vc, animated: true, completion: nil)
}

Related

How to add PDF attachment while sending sms in Swift

if (MFMessageComposeViewController.canSendText())
{
let controller = MFMessageComposeViewController()
controller.body = ""
controller.recipients = ["1234567890"]
controller.messageComposeDelegate = self as? MFMessageComposeViewControllerDelegate self.present(controller, animated: true, completion: nil)
}
else
{
print("Cannot send the message")
}
func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult)
{
//Displaying the message screen with animation.
self.dismiss(animated: true, completion: nil)
}
while sending sms i need to attach 2 pdf i know how to add on mail but for sms i haven't found any documentation.
i have used this way for mail but how to do on messaging.
func sendEmail() {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setSubject("Invoice PDF")
do {
let attachmentData = NSData(contentsOfFile: pdfFilePath)
mail.addAttachmentData(attachmentData! as Data, mimeType: "application/pdf", fileName: "InvoicePDF")
mail.mailComposeDelegate = self
present(mail, animated: true)
}
} else {
// show failure alert
}
}
You can export files using the UIActivityViewController:
let activityVC = UIActivityViewController(activityItems: [your-data-here], applicationActivities: nil)
self.present(activityVC, animated: true, completion: nil)
If you want to limit the export options you can use the excludedActivityTypes property.

share PDF file with UIActivityViewController

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 ?
![](https://i.stack.imgur.com/ywDQw.jpg
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() {
super.viewDidLoad()
pdfView.autoScales = true
pdfView.displayMode = .singlePage
pdfView.displayDirection = .horizontal
pdfView.usePageViewController(true, withViewOptions: [UIPageViewControllerOptionInterPageSpacingKey: 20])
pdfView.document = pdfDocument
resume()
// 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) {
resume()
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) {
resume()
}
#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)
}
}
}
In SWIFT 4
#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
{
print("completed")
}
}
}
activitycontroller.excludedActivityTypes = [UIActivityType.airDrop]
activitycontroller.popoverPresentationController?.sourceView = self.view
self.present(activitycontroller, animated: true, completion: nil)
}
catch {
//ERROR
}
}
You can also share the PDF data itself using the dataRepresentation() function
guard let data = document?.dataRepresentation() else { return }
let activityController = UIActivityViewController(activityItems: [data], applicationActivities: nil)
present(activityController, animated: true)
Cheers
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 .
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)
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)
activityViewController.popoverPresentationController?.sourceView=self.view
present(activityViewController, animated: true, completion: nil)
}
else {
print("document was not found")
}
Call this method on button click
func sharePdf() {
let activityViewController = UIActivityViewController(activityItems: [pdfView.document!.dataRepresentation()!], applicationActivities: nil)
present(activityViewController, animated: true)
}
For sharing image just change the activity item
func shareImg() {
let activityViewController = UIActivityViewController(activityItems: [imageView.image!], applicationActivities: nil)
present(activityViewController, animated: true)
}
You can share multiple items at once, by adding it in activityItems array

How to get and show screenshot in share button?

Below I have tried to code so the screenShot function will take a full screenshot of my viewController. I am trying to figure out how I could take the screenshot and put it in into my activityItems in the sharePressed action, so it will show the screenshot when you try to share.
func captureScreen() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
#IBAction func sharePressed(_ sender: Any) {
let activityVC = UIActivityViewController(activityItems: [""], applicationActivities: nil)
activityVC.popoverPresentationController?.sourceView = self.view
self.present(activityVC, animated: true, completion: nil)
}
#IBAction func sharePressed(_ sender: Any) {
let imgScreenshot = captureScreen()
if let imgScreenshot = imgScreenshot {
let objectsToShare = ["Post message", imgScreenshot] as [Any]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityVC.excludedActivityTypes = [UIActivityType.airDrop, UIActivityType.addToReadingList]
self.present(activityVC, animated: true, completion: nil)
}
}

iOS : activityType doesn't work on UIactivityViewController

hi this is my code I have implement UIactivityViewCotroller but when I click I don't see mail and Facebook app
#IBAction func activityView(_ sender: UIButton) {
let text = "This is some text that I want to share."
let textToShare = [ text ]
let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook, UIActivityType.mail ]
self.present(activityViewController, animated: true, completion: nil)
}
but I don't see those app
what should I do?
Replace the function as follows
#IBAction func activityView(_ sender: UIButton) {
let text = "This is some text that I want to share."
let textToShare = [ text ]
let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
activityViewController.excludedActivityTypes = [ UIActivityType.airDrop ]
self.present(activityViewController, animated: true, completion: nil)
}
Activity Controllers excludedActivityTypes means you are excluding those sharing options to list in activityController

UIActivityController to share URL file

I want to share an URL file that has been created in the app and a text. But it seems it only can share text and not any data like URL or UIImage.
The code I am using:
let sharedVideo = Video(Title: _data[1], VideoID: _data[0], Duration: _data[3], ViewCount: _data[2])
let sharedURL = VideoManager.exportData(video: sharedVideo)
let shareItems:Array = [sharedURL,"check this out baby!"] as [Any]
let activityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
Also I use an UIImage object instead of sharedURL to see If it has problem with URL or not.
It doesn't work even with an image file. When I click on share button inside UIActivityViewController, It works just for text, no URL nor image.
I am using Swift 3 in Xcode 8.
Thanks.
PS: I am sure about sharedURL object that it isn't nil nor undefined.
Try this:
#IBAction func btnExport(sender: AnyObject)
{
let someText:String = "Hello want to share text also"
let objectsToShare:URL = URL(string: "http://www.google.com")!
let sharedObjects:[AnyObject] = [objectsToShare as AnyObject,someText as AnyObject]
let activityViewController = UIActivityViewController(activityItems : sharedObjects, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook,UIActivityType.postToTwitter,UIActivityType.mail]
self.present(activityViewController, animated: true, completion: nil)
}
Simplified solution working with Swift 5+
let url = URL(string: shareUrlString)!
let text = "Some text that you want shared"
let activity = UIActivityViewController(activityItems: [url, text], applicationActivities: nil)
present(activity, animated: true)

Resources