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"
}
}
HelperClass.shared.showActivityController()
You don't need when you are in main thread only. So writing DispatchQueue
is redundant
But in case if you want to present from another thread it will be a must for you presenting the UI using DispathchQueue
Suppose , you are making a network call and and after the completion of network call you have to show UI
From my point of view, you should remove the dispatch queue from the method.
func showActivityController(){
let items = [self]
let activityController = UIActivityViewController(activityItems: items, applicationActivities: nil)
UIApplication.shared.keyWindow?.rootViewController?.present(activityController, animated: true)
}
But when you have to present the UI from other thread, just call the method in main thread
DispatchQueue.main.async {
HelperClass.shared.showActivityController()
}