charliework
charliework

Reputation: 33

Protocol delegate not working sometimes

I am having an issue with a protocol delegate not always responding. Here is my implementation:

protocol CameraViewDelegate: class {
    func didTapCancel(sender: CameraView)
    func didFinishSelectingPhoto(image: UIImage, sender: CameraView)
}

In the CameraView class I have:

weak var delegate: CameraViewDelegate?

and

@IBAction func cancelButtonTapped() {
    delegate?.didTapCancel(self)
}

@IBAction func sendPhotoTapped() {
    if let image = selectedImage {
        delegate?.didFinishSelectingPhoto(image, sender: self)
    }
}

In the other class, I have:

class PhotoController: CameraViewDelegate {

and

func didTapCancel(sender: CameraView) {
    dismissViewControllerAnimated(true, completion: nil)
    RootViewController.shared().navigateToHome()
}

func didFinishSelectingPhoto(image: UIImage, sender: CameraView) {
    let photo = MyPhoto(image: image)
    sendPhoto(photo)
    dismissViewControllerAnimated(true, completion: nil)
}

This works 95% of the time, but I am getting a weird bug where the delegate fails to respond sometimes. If I hit the button cancel or sendPhoto, the button appears to press but nothing happens. I know this is the delegate failing to respond because the other buttons in CameraView that don't use the delegate still work normally.

Any ideas?

Upvotes: 2

Views: 737

Answers (3)

Ender
Ender

Reputation: 13

Check if you set delegate when you initialize your camera view. Try something like:

let cameraView = CameraView() 
cameraView.delegate = self

Upvotes: 0

Paulo Mattos
Paulo Mattos

Reputation: 19339

Debugging Tip. Try to temporarily remove the weak qualifier from your delegate property. You might be releasing your delegate object too soon (i.e., zero strong references to it).

If this fixes your issue, then you found your bug, congrats! Please insert again the weak qualifier so you don't leak memory unnecessarily — and remember to keep a strong reference to it elsewhere :-)

Upvotes: 3

Arvind Patel
Arvind Patel

Reputation: 1

I think you have to assign other view controller delegate = self where you from push the camera

Upvotes: 0

Related Questions