-1

I am trying to make my app so that when a user touches a UIImageView A certain sound will play. However, while that sound is playing, I want the UIImageView.isUserInteractionEnabled to be assigned to false. Once the sound is done playing I want the UIImageView.isUserInteractionEnabled to be assigned to true. When ever I run the following code I get an error in the card class, even if I force unwrap. Below is the class that contains the image view I want to disable.

class SecondViewController: UIViewController , UIGestureRecognizerDelegate  {
@IBOutlet weak var imgPhoto: UIImageView!

 func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
   imgPhoto.isUserInteractionEnabled = false
    itemList[imageIndex].playSound()

}
}

This is the class where the playSound func is located.

import Foundation; import UIKit; import AVFoundation

class Card: NSObject
{
var player: AVAudioPlayer?
var svc = SecondViewController()

var image: UIImage
var soundUrl: String

init(image: UIImage, soundUrl: String, isActive:Bool = true) {
    self.image = image
    self.soundUrl = soundUrl

}
func playSound()
{
    guard let url = Bundle.main.url(forResource: self.soundUrl, withExtension: "m4a") else { return }
    do
    {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        player = try AVAudioPlayer(contentsOf: url)
        player?.delegate = self
        guard let player = player else { return }
        player.prepareToPlay()
        player.play()
        audioPlayerDidFinishPlaying(player)


        print("play")
    } catch let error {
        print(error.localizedDescription)
    }
}
}

extension Card: AVAudioPlayerDelegate  {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer){
 svc.imgPhoto.isUserInteractionEnabled = true
    }
}

this is the error I get enter image description here

Anthony Rubin
  • 69
  • 1
  • 1
  • 14

1 Answers1

1

The problem is this line:

var svc = SecondViewController()

That svc is not your SecondViewController, the existing one in the interface with an imgPhoto. Instead, you are creating a new, separate, and above all blank view controller with an empty view, so its imgPhoto is nil and you crash when you refer to it.

What you want to do is use the "delegate" pattern to hold a reference to the real SecondViewController so you can talk to it.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Compare https://stackoverflow.com/questions/48793064/swift-4-switch-page-view-controller-programatically and many many many others. This is a common mistake, caused by a failure to understand the difference between class and instance. – matt Mar 21 '18 at 21:42