Search code examples
iosswiftuiimagepickercontroller

Function created, but never called, yet it is still executed


I am very new to iOS development and Swift, so sorry if this is a trivial question. I have the following code

import UIKit

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    var imagePicker: UIImagePickerController!

    @IBOutlet weak var imageView: UIImageView!

    @IBAction func openGalery(_ sender: UIButton) {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary;
            imagePicker.allowsEditing = true
            present(imagePicker, animated: true, completion: nil)
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        imagePicker.dismiss(animated: true, completion: nil)
        imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

In the code I create the func imagePickerController. imagePickerController is responsible for setting the selected image in the imageView. It works. I open the galery, I select an image and there is a transition back to the view with the image set. However, why is it working? I never call the function imagePickerController. Comparing this with the languages I worked before, I should call this function on tap of the select button in the PhotoLibrary. Like an event or something. But here it is somehow called automatically, only by defining the function. Why is that?


Solution

  • imagePicker.delegate = self

    Translates to: "Hey imagePicker, when something happens, let me know by calling my UIImagePickerControllerDelegate methods!"

    In particular, your implementation of imagePickerController(_:didFinishPickingMediaWithInfo:) is being called, which is part of the UIImagePickerControllerDelegate protocol.