Search code examples
iosswiftuialertcontrolleruiactivityviewcontroller

open UIActivityViewController after UIAlertController fails


I need to have a function, to share some .csv files via e-mail.

So first I am going to save the .csv files to the document directory and afterwards I am trying to open an UIActivityViewController.

But this fails.

This is my code:

saveprojectfile() // Here are the UIAlertController calls, these calls needs some time

let activityVC = UIActivityViewController(activityItems: [path], applicationActivities: nil)
activityVC.popoverPresentationController?.sourceView = self.view

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

Any hints, why this isn't working?

Thanks!


Solution

  • The UIActivityViewController code is being executed while the UIAlertController is displayed, but it cannot present while the alert controller is displayed. I would have thought this would crash.

    You should display the activity view controller in the completion handler of the alert controller action.

    // Code for alert controller (was in your saveprojectfile() function
    let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: yourFunction)) // OK action handler added
    self.present(alert, animated: true, completion: nil) // Completion handler here will not work as it fires on completion of presenting, not dismissing
    
    func yourFunction() {
        // Present the action controller here
        let activityVC = UIActivityViewController(activityItems: [path], applicationActivities: nil)
        activityVC.popoverPresentationController?.sourceView = self.view
        self.present(activityVC, animated: true, completeion: nil)
    }