audioPlayerDidFinishPlaying 函数问题

audioPlayerDidFinishPlaying func issues

我正在尝试让我的应用程序在用户触摸 UIImageView 时播放特定的声音。但是,在播放该声音时,我希望将 UIImageView.isUserInteractionEnabled 分配给 false。声音播放完毕后,我希望将 UIImageView.isUserInteractionEnabled 分配给 true。每当我 运行 以下代码时,即使我强制解包,我也会在卡 class 中收到错误。下面是包含我要禁用的图像视图的 class。

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

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

}
}

这是 playSound 函数所在的 class。

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
    }
}

这是我得到的错误

问题出在这一行:

var svc = SecondViewController()

那个svc不是你的SecondViewController,界面中已有一个imgPhoto。相反,您正在创建一个新的、独立的,最重要的是 blank 视图控制器,它有一个空视图,所以它的 imgPhotonil 并且当您引用时崩溃

您想要做的是使用 "delegate" 模式来保存对 real SecondViewController 的引用,以便您可以与其对话。