Asutosh Patra Asutosh Patra - 1 year ago 166
iOS Question

How to dismiss the UIActivityViewController on clicking the Cancel button?

let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
let excludeActivities = [UIActivityTypeAirDrop, UIActivityTypePrint, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr, UIActivityTypePostToVimeo,UIActivityTypeMail,UIActivityTypeOpenInIBooks,UIActivityTypeCopyToPasteboard]

let nav = UINavigationController(rootViewController: activityVC)
nav.modalPresentationStyle = UIModalPresentationStyle.Popover
let popover = nav.popoverPresentationController as UIPopoverPresentationController!
activityVC.preferredContentSize = CGSizeMake(0,150)
popover.sourceView = self.view
popover.sourceRect = CGRectMake(345,580,0,0)
self.presentViewController(nav, animated: true, completion: nil)

I'm trying to dismiss the activity controller when cancel button is clicked but this is not working.
On clicking anywhere outside the controller,this gets dismissed but not by tapping cancel button.

Answer Source

Just use this

 let text = String(format:"Download the app on your iPhone")

                        // set up activity view controller
                        let objectsToShare: [AnyObject] = [ text ]
                         self.activityViewController = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
                        self.activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
                        self.activityViewController.completionWithItemsHandler = { activity, success, items, error in
                            if success {
                                // Success handling here

                        // exclude some activity types from the list (optional)
                        self.activityViewController.excludedActivityTypes = [ UIActivityTypeAirDrop, UIActivityTypePostToFacebook ]

                        // present the view controller
                        self.presentViewController(self.activityViewController, animated: true, completion: nil)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download