How to perform an action after calling UIActivityViewController and then closing

I cannot figure out how to perform actions after the call UIActivityViewController. For example, when I save an image with the following code:

let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let activity = UIActivityViewController(activityItems: [image], applicationActivities: nil)
presentViewController(activity, animated: true, completion: nil)

The user receives a new window with the ability to save the image somewhere. After the image has been successfully saved, I want to perform some action (for example, go to the root controller). But I can’t figure out how to track that this one has UIActivityViewControllerbeen closed. If I write code after this block, nothing happens, as I understand it, because this code is implemented in the VC action, and not in the original VC.

I thought viewWillDisappearit would help me, but it keeps track of the original VC, from where I called the VC activity, and I cannot figure out how I can track the VC activity. At the same time, even if I had the opportunity to track this event, the question still remains: how can I distinguish a successful save from a cancel?

+4
source share
2 answers

You can use completionHadler, in this case:

activity.completionWithItemsHandler = { activity, success, items, error in
    print("activity: \(activity), success: \(success), items: \(items), error: \(error)")
}
+9
source

You must use the protocols to call the method when closing the UIActivityViewController

protocol ActivityViewControllerDelegate {
    activityViewControllerClosed()
}

class YourOriginalViewController: UIViewController, ActivityViewControllerDelegate {
    func yourMethodToOpenTheActivityViewController() {
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        let activity = UIActivityViewController(activityItems: [image], applicationActivities: nil)

        activity.delegate = self  //ADD SELF AS THE DELEGATE

        presentViewController(activity, animated: true, completion: nil)
    }

    func activityViewControllerClosed() {
        //Your UIActivityViewController has been closed, you can do something here
    }
}

class UIActivityViewController: UIViewController {
    var delegate: ActivityViewControllerDelegate? //ADD A PROPERTY FOR THE DELEGATE

    func yourMethodToCloseTheActivity() {
        delegate.activityViewControllerClosed() //ADD THIS LINE TO NOTIFY THE DELEGATE
    }
}

you can find more information here https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

0

Source: https://habr.com/ru/post/1611341/


All Articles