Search code examples
swiftnotificationcenter

Call a function in viewcontroller with parameter from another class


I have a class named CameraManager. It inherits from UINavigationControllerDelegate and UIImagePickerControllerDelegate.

In func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) I want to call setImageInImageView(image:UIImage) function that is in viewcontroller and pass the photo taked by user to it.

Here is my wrong code in CameraManager class.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    ViewController.setImageToImageView(theImage: chosenImage) // wrong code
}

I know I can set the photo in different ways, like create an outlet to imageview in my CameraManager class, or viewcontroller inherits UINavigationControllerDelegate and UIImagePickerControllerDelegate.

But I want do this in separated class. After some searches I found NotificationCenter, but it's complex for a swift beginner like me and there is few resources in swift 3 with passing parameter.


Solution

  • You can pass your opened ViewController object to CameraManager class and in func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) you can openViewControllerObject.setImageToImageView(theImage: chosenImage).