Swift协议函数永远不会被调用

时间:2018-03-23 20:29:03

标签: ios swift avaudioplayer delegation

我目前正在处理在播放AVAudioPlayer时禁用UIImageView的代码。我要禁用的AVAudioPlayer和ImageView位于两个不同的类中。我试着写一个委托让我的两个班级沟通。由于某种原因,即使我的类符合协议,调用方法并将委托设置为self,协议方法也永远不会运行。在我的Card类中,在audioDidFinishPlaying方法中,我安全地打开了委托。当我运行我的代码时,每次调用print语句而不是isOn方法。有人可以就这个问题提出任何建议吗?

包含我的AVAudioPlayer的类的代码在

之下
import Foundation; import UIKit; import AVFoundation

protocol isOnProtocol{
func isOn()
}

class Card: NSObject
{
    var delegate: isOnProtocol?
    var player: AVAudioPlayer?
    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){
        if let del = delegate{
            del.isOn()
        }else{
            print("the delegate is not set")
        }

    }
}

我正在尝试与之通信的ViewController的代码如下。当调用图像分接功能时,声音播放并且UserInteractions应该为假,直到AVAudioPlayer完成(调用isOn函数)。

import UIKit



class SecondViewController: UIViewController , UIGestureRecognizerDelegate, isOnProtocol  {



@IBAction func home(_ sender: Any) {
    performSegue(withIdentifier: "home", sender: self)
}

@IBOutlet weak var imgPhoto: UIImageView!


var imageIndex: Int = 0
var itemList:[Card] = []


func addlist(list:[String])
{
    for word in list
    {
        itemList.append(Card(image: UIImage(named: word)!, soundUrl: word))
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    for i in 0..<11 {
        let list: [String]
        switch i {
        case 0: list = ["lake", "lamb", "lamp", "lark", "leaf", "leash", "left", "leg", "lime", "lion", "lips", "list", "lock", "log", "look", "love", "lunch"]
        case 1: list = ["ladder", "ladybug", "laughing", "lawnmower", "lemon", "leopard", "leprechaun", "letters", "licking", "lifesaver", "lifting", "lightbulb", "lightning",
                 "listen", "llama"]
        case 2: list = ["alligator", "balance", "ballerina", "balloon", "bowling", "cello", "colors", "curlyhair", "dollar", "dolphin", "elephant", "eyelashes", "gasoline",

                 "goalie", "hula", "jellyfish", "olive", "pillow", "pilot", "polarbear", "rollerskate", "ruler", "silly", "telephone", "television", "tulip", "umbrella", "valentine",

                 "violin", "yellow", "xylophone"] //yellow xylophone
        case 3: list = ["apple", "ball", "bell", "bubble", "castle", "fall", "fishbowl", "girl", "owl", "pail", "peel", "pool", "smile", "whale", "wheel"] //whale wheel
        case 4: list = ["planet", "plank", "plant", "plate", "play", "plum", "plumber", "plus"]
        case 5: list = ["black", "blanket", "blender", "blocks", "blond", "blood", "blow", "blue"]
        case 6: list = ["flag", "flipflop", "float", "floor", "flower", "fluffy", "flute", "fly"]
        case 7: list = ["glacier", "glad", "glasses", "glide", "glitter", "globe", "glove", "glue"]
        case 8: list = ["clam", "clamp", "clap", "claw", "clean", "climb", "clip", "cloud"]
        case 9: list = ["sled", "sleep", "sleeves", "slice", "slide", "slime", "slip", "slow"]
        case 10: list = ["belt", "cold", "dolphin", "elf", "golf", "melt", "milk", "shelf"]
        default: fatalError()

        }
        if UserDefaults.standard.value(forKey: "\(i)") as? Bool ?? true {
        addlist(list:list)
        }
    }
   print(itemList.count)


    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
    imgPhoto.isUserInteractionEnabled = true
    imgPhoto.addGestureRecognizer(tapGestureRecognizer)


    imgPhoto.image =  itemList[0].image

    // Do any additional setup after loading the view.
    //imgPhoto.isUserInteractionEnabled = true

    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:)))
    leftSwipe.cancelsTouchesInView = false

    let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:)))
    rightSwipe.cancelsTouchesInView = false

    leftSwipe.direction = .left
    rightSwipe.direction = .right

    view.addGestureRecognizer(leftSwipe)
    view.addGestureRecognizer(rightSwipe)

}



@IBAction func memoryButton(_ sender: Any) {
  performSegue(withIdentifier: "memory", sender: self)

}



func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
imgPhoto.isUserInteractionEnabled = false
let card = itemList[imageIndex]
card.delegate = self
card.playSound()
}
internal func isOn() {
    imgPhoto.isUserInteractionEnabled = true
}


func Swiped(gesture: UIGestureRecognizer) {
    imgPhoto.isUserInteractionEnabled = true

    if let swipeGesture = gesture as? UISwipeGestureRecognizer {

        switch swipeGesture.direction {

        case UISwipeGestureRecognizerDirection.right :
            print("User swiped right")

            // decrease index first

            imageIndex -= 1

            // check if index is in range

            if imageIndex < 0 {

                imageIndex = itemList.count - 1

            }
            UIImageView.transition(with: imgPhoto, duration: 0.3, options: .transitionFlipFromLeft, animations: nil, completion: nil)
            imgPhoto.image = itemList[imageIndex].image

        case UISwipeGestureRecognizerDirection.left:
            print("User swiped Left")

            // increase index first

            imageIndex += 1

            // check if index is in range

            if imageIndex > itemList.count - 1 {

                imageIndex = 0

            }
             UIImageView.transition(with: imgPhoto, duration: 0.3, options: .transitionFlipFromRight, animations: nil, completion: nil)
            imgPhoto.image = itemList[imageIndex].image
        default:


            break //stops the code/codes nothing.
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

您的卡片实例不是播放声音的卡片,您可以在viewDidLoad中删除卡片实现,并且您必须在从itemList数组中获取的卡片对象中设置委托:

func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
    imgPhoto.isUserInteractionEnabled = false
    let card = itemList[imageIndex]
    card.delegate = self
    card.playSound()
}