KSigWyatt KSigWyatt - 1 year ago 210
Swift Question

UIActivityViewController in iOS 10

Anyone know how to use UIActivityView in iOS 10? Now that for some reason in Swift 3.0 it will compile and build but when the application is running after pressing a share button using the following code results in an application crash... it worked perfectly in iOS 9.3 and Swift 2.0.

As specified in the comments of the code line 6 or

let objectsToShare = [textToShare] as! AnyObject
causes a Thread1: signal SIGABRT and application crash

@IBOutlet weak var detailDescriptionLabel: UITextView!

@IBAction func share(_ sender: AnyObject) {
let textToShare = detailDescriptionLabel.attributedText

let objectsToShare = [textToShare] as! AnyObject
// line above causes app crash in iOS 10 - compiled and built
// error is "Thread1: signal SIGABRT"

let activityVC = UIActivityViewController(activityItems: objectsToShare as! [AnyObject], applicationActivities: nil)

activityVC.popoverPresentationController?.sourceView = (sender as! UIView)
self.present(activityVC, animated: true, completion: nil)

class ActivityForNotesViewController: UIActivityViewController {

internal func _shouldExcludeActivityType(_ activity: UIActivity) -> Bool {
let activityTypesToExclude = [
//insert UIActivity here

if let actType = activity.activityType {
if activityTypesToExclude.contains(actType) {
return true
else if super.excludedActivityTypes != nil {
return super.excludedActivityTypes!.contains(actType)
return false

Anyone that can help me I'd appreciate it.

Answer Source

I think I may have answered my own question, but if someone can double check I'd appreciate it. The comments in the code are the various changes that I made to get this fix to work. Works in iOS 10 in Simulator and a real device.

@IBAction func share(_ sender: AnyObject) {
        // Changed attributedText to text!
        let textToShare = detailDescriptionLabel.text!

        // Removed Cast to AnyObject
        let objectsToShare = [textToShare]

        //Removed cast to AnyObject in the Function Call to get rid of error from removing it above
        let activityVC = UIActivityViewController(activityItems: objectsToShare , applicationActivities: nil)

//Moved cast for as! UIView outside the perantheses of sender so 
//that the as! can be used more efficiently. But most importantly
// I changed the as! to a as? instead thinking that might catch an error and it did... so this works.

        activityVC.popoverPresentationController?.sourceView = (sender) as? UIView
                self.present(activityVC, animated: true, completion: nil)