如何在UIActivityViewController调用然后关闭

时间:2015-10-12 21:24:42

标签: ios swift uiactivityviewcontroller

我无法理解在调用UIActivityViewController后如何执行操作。 例如,当我使用以下代码保存图像时:

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

用户收到新窗口,可以在某处保存图像。成功保存图像后,我想执行一些操作(例如跳转到根视图控制器)。但我无法弄清楚如何跟踪此UIActivityViewController已关闭。如果我在这个块之后编写代码,没有任何反应,正如我所理解的那样,因为这个代码是在活动VC中实现的,而不是在原始VC中实现的。

我认为viewWillDisappear会对我有所帮助,但它跟踪原始VC,我称之为活动VC,我无法弄清楚如何跟踪活动VC。与此同时,即使我有能力追踪此事件,仍然存在一个问题:除了取消之外,我怎么能有所不同?

2 个答案:

答案 0 :(得分:17)

在这种情况下,您可以使用completionHadler

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

答案 1 :(得分:-2)

当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
    }
}

您可以在https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

找到更多信息