Mateo Villagomez Mateo Villagomez - 3 months ago 7
Swift Question

Is it possible to have a function inside a completion handler?

Is it possible to have a function inside a completion handler?

I want to save an image through a function after the user shared that same image in activity controller.
I want to do the following:

let controller = UIActivityViewController(activityItems: [generateMemedImage()], applicationActivities: nil)
self.presentViewController(controller, animated: true, completion: nil)
controller.completionWithItemsHandler = {
// Have this save() function when the activity has been completed
func save() {
//Save the meme
let meme = Meme(topText: self.upperTextField.text!, lowerText: self.lowerTextField.text!, originalImage:
self.imageRetrieved.image!, memedImage: generateMemedImage())
}
}


Is there any better solution? Or how can I achieve this?

Answer

You don't need to declare a function inside the completion handler. Just write the code to perform the saving inside it, look

class Controller: UIViewController {

    func foo() {
        let controller = UIActivityViewController(activityItems: [generateMemedImage()], applicationActivities: nil)
        self.presentViewController(controller, animated: true, completion: nil)
        controller.completionWithItemsHandler = { activityType, completed, returnedItems, error -> () in
            // write code to perform the save here <---
        }
    }

    func generateMemedImage() -> [AnyObject] {
        return []
    }

}
Comments