swift : UIPickerViewController delegates not calle

2019-07-25 07:16发布

问题:

I am working on an app which requires user to take selfie of pick Images from different ViewController. I want to extract class just for this purpose. But after extraction of class the delegate methods of UIPickerViewController are not being called.

right now, I have a class called MultiMediaManager inside MultiMediaManager.swift file.

    class MultiMediaManager: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {


    let imagePicker = UIImagePickerController()
    var viewController: UIViewController?
    var delegate: MultiMediaManagerDelegate?

    init(presentingViewController: UIViewController) {
        viewController = presentingViewController
        super.init()
        imagePicker.delegate = self
    }

    func showPictureSourceOptions() {
        var presentationStyle: UIAlertControllerStyle = .ActionSheet
       let galleryAction = UIAlertAction(title: "Photo Library", style: UIAlertActionStyle.Default) { (action) in
            self.showPhotoGallery()
        }
        alertController.addAction(galleryAction)
        self.viewController?.presentViewController(alertController, animated: true, completion: nil)
    }

    private func showPhotoGallery() {
        imagePicker.allowsEditing = false
        imagePicker.sourceType = .PhotoLibrary
        viewController?.presentViewController(imagePicker, animated: true, completion: nil)

      // every thing is working till here as expected.
     // note: here, debugger prints MultiMediaManager as imagePicker.delegate 
    }

The View to pick and choose the picture from gallery is presented. But When I choose image, the viewcontroller just dissmiss silently and its delegate is not called.

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    // break point does not stop here. nither print statement work.

      viewController?.dismissViewControllerAnimated(true, completion: nil)
}

I have been scratching my head the whole day, But I still don't have any idea what's going on.

回答1:

There was nothin wrong with these code. The problem was the way it was called.

func showPictureSourceOptions() {
        var mediaManager = MultiMediaManager(presentingViewController: self)
        mediaManager!.showPictureSourceOptions()
    }

I was creating new local variable of mediaManager every time the function was called. removing the var In front of the mediaManager fixed the problem.