Phillip Phillip - 1 month ago 5
Swift Question

UIActivityView Button Error

I'm trying to use UIActivityView to create a sharing button for my app. When I press the button in the app I get an error. What's wrong with the code?

@IBAction func shareButton(_ sender: UIButton) {

let texttoshare = "Sharing"
let URLtoshare = NSURL(string: "www.google.com")
let objectsToShare:NSArray = [texttoshare, URLtoshare!]
let activityVC = UIActivityViewController(activityItems: objectsToShare as! [Any], applicationActivities: nil)

self.present(activityVC, animated: true, completion: nil)

}
}


The error: is Thread 1: signal SIGABRT

Answer

Try this. At least, it's working for me without errores..

let texttoshare = "Sharing"
let URLtoshare = URL(string: "www.google.com")
let activityVC = UIActivityViewController(activityItems: [texttoshare, URLtoshare!], applicationActivities: nil)
self.present(activityVC, animated: true, completion: nil)

If you want to use UIActivityViewController for iPads, you need to specify popoverPresentationController?.sourceView for activityVC. For example:

let texttoshare = "Sharing"
let URLtoshare = URL(string: "www.google.com")
let activityVC = UIActivityViewController(activityItems: [texttoshare, URLtoshare!], applicationActivities: nil)
activityVC.popoverPresentationController?.sourceView = button...
self.present(activityVC, animated: true, completion: nil)