I'm trying to present the UIActivityViewController
in multiple parts of my app by enclosing it in a helper class. The following code works fine, I can call the showActivityController()
method from any other view controllers in my app, and the UIActivityViewController
gets presented as expected.
My question is, do I really need to enclose the code to present the UIActivityViewController
within the DispatchQueue.main.async
as shown below?
I tried it without it and it works fine but I want to make sure that leaving it there won't cause any issues later on.
class HelperClass: UIViewController, UIActivityItemSource{
static let shared = HelperClass()
func showActivityController(){
DispatchQueue.main.async {
let items = [self]
let activityController = UIActivityViewController(activityItems: items, applicationActivities: nil)
UIApplication.shared.keyWindow?.rootViewController?.present(activityController, animated: true)
}
}
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return "Return Type"
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
if activityType == .message{
return "Text for iMessage"
}else if activityType == .mail{
return "Text for Email"
}else{
return "Text for all other apps"
}
}
func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
return "Email Subject"
}
}
Usage from other View Controllers
HelperClass.shared.showActivityController()